Static Import: Importing Static Members
You'll learn how to import static methods and fields directly, eliminating the need to repeatedly type class names.
The Core Idea
Normally, when you use static methods or constants from another class, you must qualify them with the class name—like Math.sqrt(4) or Integer.MAX_VALUE. Static imports allow you to bring these static members directly into your current namespace, so you can write simply sqrt(4) or MAX_VALUE instead.
Think of it like adding a specialized tool directly to your workbench instead of walking to a toolbox every time you need it.
Static Import Syntax
There are two forms:
Single static member import:
import static java.lang.Math.sqrt;
import static java.lang.Integer.MAX_VALUE;
Import all static members from a class:
import static java.lang.Math.*;
Using Static Imports
import static java.lang.Math.PI;
import static java.lang.Math.pow;
public class Circle {
public double area(double radius) {
return PI * pow(radius, 2); // No Math. prefix needed
}
}
Without static import, you'd write Math.PI * Math.pow(radius, 2).
When to Use Static Imports
Static imports work best with:
- Mathematical constants and functions you use frequently
- Utility methods called repeatedly in one file
- Constants from enums or constant classes
Avoid overusing them—importing too many static members can make code harder to read, as it becomes unclear where methods come from.
Key Takeaway:
Static imports let you use static methods and fields without class qualification, reducing verbosity when working intensively with specific utility classes or constants, but should be used judiciously to maintain code clarity.