Sub topic 10
Static imports
This chapter assumes you can write a class in a package, use a single-type import, and compile and run packaged code with javac -d and java -cp. Earlier chapters covered those topics.
What a static import does
A normal import lets you write Product instead of com.example.shop.model.Product. A static import does the same for the static members of a class: static methods, static fields and static nested types. You can write max(3, 7) instead of Math.max(3, 7), and PI instead of Math.PI.
import static java.lang.Math.PI;
import static java.lang.Math.max;
public class StaticImportDemo {
public static void main(String[] args) {
System.out.println(max(3, 7));
System.out.println(PI);
}
}The keyword order is import static, not static import. The name after it must be a class or interface, written with its fully qualified name, followed by a member name or *.
A static import changes only how you write a name. It doesn't copy code, change how the class is loaded, or create a dependency that a qualified call wouldn't create. The compiler produces the same bytecode for max(3, 7) and Math.max(3, 7).
The two forms
| Form | Example | What it brings in |
|---|---|---|
| Single-static-import | `import static java.lang.Math.sqrt;` | Every accessible static member named `sqrt`: all overloads, plus any field or nested type with that name |
| Static-import-on-demand | `import static java.lang.Math.*;` | All accessible static members of `Math` |
A single-static-import named max imports every overload of max. You can't pick one signature.
Here is a complete program that uses the single form:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
public class Geometry {
static double circleArea(double radius) {
return PI * pow(radius, 2);
}
static double hypotenuse(double a, double b) {
return sqrt(pow(a, 2) + pow(b, 2));
}
public static void main(String[] args) {
System.out.printf("%.2f%n", circleArea(2));
System.out.printf("%.2f%n", hypotenuse(3, 4));
}
}It prints 12.57 and then 5.00.
What you can and can't import
You can import these members:
- Static methods, such as
Math.sqrt. - Static fields, including constants such as
Math.PIand enum constants such asTimeUnit.SECONDS. - Static nested types, such as
Map.Entry. For nested types,import static java.util.Map.Entry;andimport java.util.Map.Entry;have the same effect.
You can't import these members:
- Instance methods and instance fields. They need an object, so there is no simple name that could refer to them.
- Members that aren't accessible from your class. A private member never imports. A package-private member imports only if your class is in the same package.
- Anything from a class in the default package, because that package has no name to write after
import static.
A static import of a member doesn't import the class itself. The next program imports entry but still needs a normal import of Map, because it writes Map.ofEntries.
import static java.util.Map.entry;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Map;
public class Units {
public static void main(String[] args) {
Map<String, Long> timeouts = Map.ofEntries(
entry("connect", SECONDS.toMillis(2)),
entry("read", SECONDS.toMillis(30)));
System.out.println(timeouts.get("connect"));
}
}This prints 2000. Notice that SECONDS is an enum constant, so SECONDS.toMillis(2) calls an instance method on the imported static field. That is allowed. Only the imported name has to be static.
How the compiler resolves a simple method name
When your code calls max(a, b), the compiler doesn't look at the static imports first. It searches in this order:
- The current class, including inherited members, then each enclosing class outward. If any of them has a method named
max, the search stops there. Only that class's methods namedmaxare candidates. - If no enclosing class has a method named
max, the compiler looks at the static imports. A single-static-import shadows an on-demand import for the same name. - Overload resolution then picks among the candidates by argument types.
Step 1 causes the most surprises. Suppose you import Math.max and then declare your own three-argument helper with the same name:
import static java.lang.Math.max;
public class Largest {
static int largest(int a, int b, int c) {
return max(max(a, b), c);
}
public static void main(String[] args) {
System.out.println(largest(4, 9, 6));
}
}This program compiles and prints 9. Now rename largest to max. The method max(int, int, int) is now a member of the class, so it hides every imported max. The inner call max(a, b) has two arguments, and the compiler finds only the three-argument method. It reports an error, even though Math.max(int, int) is imported. The fix is to call Math.max(a, b) explicitly or to choose a different method name.
Ambiguity between two static imports
Two on-demand static imports can bring in the same name. The conflict is reported only when you use the name.
import static java.lang.Integer.*;
import static java.lang.Math.*;Both Integer and Math declare max(int, int). A call such as max(1, 2) is ambiguous and doesn't compile. The import lines themselves are legal. Likewise, if both classes declare a static field with the same name, only using that simple name fails.
To resolve the conflict, use a single-static-import for the one you want:
import static java.lang.Integer.*;
import static java.lang.Math.*;
import static java.lang.Math.max;With the extra line, max refers to Math.max, because a single import shadows on-demand imports. This also hides Integer.max. Other names from Integer, such as MAX_VALUE and parseInt, still come from the wildcard.
Mixing the two wildcards is a bad idea in the first place. If either class gains a new static method later, it can silently create a conflict in your file.
Where static imports help and where they hurt
Static imports are worth using in a few situations:
- Repeated math or constant use. A numeric class that calls
sqrt,powandPImany times reads more clearly without theMath.prefix. - Test assertions. Test code usually writes
assertEquals(expected, actual)rather thanAssertions.assertEquals(...). The method names are distinctive and the context is obvious. - Fluent or DSL-style APIs.
Collectors.toList()andComparator.comparing(...)read well as bare names in stream pipelines, where the surrounding code makes the origin clear. - Enum constants that are used often and have unmistakable names.
They hurt readability when the names are generic. A bare call to of(...), get(...), create() or valueOf(...) tells the reader nothing about where it comes from. A wildcard static import makes the problem worse, because the reader must check every imported class to find a name's origin.
Practical rules:
- Prefer single-static-imports over
*. The import list then documents exactly which names you rely on. - Import only a handful of members per class. If you import ten static methods from five classes, use qualified names instead.
- Don't use the "constant interface" trick, where a class implements an interface just to inherit its constants. A static import gives you the same short names without making the constants part of your class's public type.
Compiling and running
Static imports don't change the build commands. The compiler needs the imported class on its classpath, just as it does for a normal import. The JDK classes used in this chapter are always available, so these commands work with the programs above:
javac -d out Geometry.java Units.java Largest.java
java -cp out GeometryFor your own classes, the import names the fully qualified class, such as import static com.example.shop.model.Prices.format;, and that class must be public with a public (or accessible) static member.
Exercise
A file contains import static java.lang.Math.*; and import static java.lang.Integer.*;. The class calls abs(-5) and reads PI. Which of these uses compile, and what would you change if one fails?
Show answer
PI compiles, because only Math declares a field with that name. abs(-5) is ambiguous: both Math.abs(int) and Integer... actually Integer has no static abs, so abs(-5) also compiles and resolves to Math.abs(int). The call that would fail is max(1, 2), min(1, 2) or sum(1, 2), since both classes declare static methods with those names and signatures. The fix is to add a single-static-import such as import static java.lang.Math.max;, which shadows the on-demand imports, or to write Math.max(1, 2) explicitly. Dropping one of the wildcards avoids the whole class of problem.
Exercise
A class imports java.lang.Math.max with a static import. It also declares static int max(int a, int b, int c). Why does a call to max(2.5, 1.5) in that class fail to compile?
Show answer
Methods declared in the class (or inherited) hide every statically imported method with the same name, regardless of parameter types. The compiler considers only max(int, int, int), which doesn't accept two doubles. Call Math.max(2.5, 1.5) explicitly or rename the class's method.