Sub topic 9
Static imports
This chapter assumes you can declare static fields and static methods and call them through the class name, as in Math.max(3, 7). It also assumes you know how import statements and packages work. Here you learn how a static import removes the class-name prefix, how Java resolves the short names it creates, and when the shortcut hurts readability.
What a static import does
A normal import makes a type available by its simple name. After import java.util.List; you write List instead of java.util.List. A static import does the same for static members. After import static java.lang.Math.max; you write max(3, 7) instead of Math.max(3, 7).
import static java.lang.Math.PI;
import static java.lang.Math.max;
public class Shapes {
public static void main(String[] args) {
System.out.println(max(3, 7));
System.out.println(2 * PI * 1.0);
}
}This prints 7 and then 6.283185307179586.
A static import is a compile-time convenience only. The compiler rewrites max(3, 7) to a call on Math, so the bytecode is the same as if you had written Math.max(3, 7). The import does not load or initialize Math. The class is initialized only when running code first uses one of its members.
The two forms
| Form | Example | What it imports |
|---|---|---|
| Single-static-import | `import static java.lang.Math.max;` | Every static member named `max`: the method and all its overloads, and also a field or nested type with that name if one exists |
| Static-import-on-demand | `import static java.lang.Math.*;` | All accessible static members of `Math` |
Some points apply to both forms:
- The name after
import staticmust be a fully qualified type name, followed by a member name or*. - The type must be in a named package. You cannot statically import from a class in the default (unnamed) package.
- You can import only static members. Static members include static fields, static methods, and static nested types. Writing
import static java.lang.String.length;fails to compile becauselengthis an instance method. - The member must be accessible from where you import it. A private static field cannot be imported from another class.
- Importing a method name imports all its overloads.
import static java.lang.Math.abs;brings inabs(int),abs(long),abs(float)andabs(double).
Static nested classes are also imported this way. import static java.util.Map.Entry; and import java.util.Map.Entry; both let you write Entry<String, Integer>.
Where static imports help
Fluent APIs with many factory methods
The Collectors class is a typical case. Each method is a static factory, and the repeated prefix adds noise.
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
public class StreamImports {
public static void main(String[] args) {
List<String> upper = Stream.of("a", "b", "c")
.map(String::toUpperCase)
.collect(toList());
String joined = Stream.of("x", "y", "z")
.collect(joining(", "));
System.out.println(upper);
System.out.println(joined);
}
}The output is [A, B, C] and then x, y, z. Names such as toList and joining are specific enough that the reader still knows where they come from.
Constants from your own classes
Suppose Config lives in a package named app. This is a Config class like the one from the earlier chapter on constants.
package app;
public final class Config {
public static final int MAX_USERS = 100;
private Config() {
}
}Another class can import the constant directly:
package app.service;
import static app.Config.MAX_USERS;
public class Registration {
public static boolean hasRoom(int current) {
return current < MAX_USERS;
}
public static void main(String[] args) {
System.out.println(hasRoom(99));
System.out.println(hasRoom(100));
}
}This prints true and then false. Before static imports, programmers sometimes put constants in an interface and had their classes implement it just to get the short names. That "constant interface" pattern leaks the constants into the public type of every implementing class, and you cannot undo it later without breaking callers. A static import gets the same short names without changing the class's type.
Test code and enum constants
Test code often imports assertion methods such as assertEquals and assertTrue. Enum constants are another good fit, for example import static java.time.DayOfWeek.MONDAY;. In both cases the names are well known, and the code reads as a sentence.
How names are resolved
When you write an unqualified name like max, the compiler looks in a fixed order. Your own declarations take priority over imports.
A class member shadows an import
A field or method declared in your class hides a static import of the same name.
import static java.lang.Math.PI;
public class ShadowDemo {
static final double PI = 3.0;
public static void main(String[] args) {
System.out.println(PI);
}
}This prints 3.0. The class's own PI wins, and the compiler gives no warning.
For methods the rule is stricter than many people expect. Shadowing is by name, not by signature. If a class declares any method named max, then every statically imported max is hidden inside that class. Suppose the class declares max(int, int, int) and you call max(1, 2). The compiler will not fall back to Math.max(int, int). It reports that no suitable method was found. To reach the imported version you must write Math.max(1, 2).
The same hiding applies to inherited members. If a superclass declares a static or instance method named max, the imported max is hidden in the subclass too. This can break code when a library adds a method to a superclass.
Single imports beat on-demand imports
A single-static-import hides a name that would also come from an on-demand import. This lets you pick one name out of a wildcard import without conflicts.
Ambiguity between on-demand imports
If two on-demand imports supply the same field name, using that name is an error. Math and StrictMath both declare PI and sqrt:
import static java.lang.Math.*;
import static java.lang.StrictMath.*;
public class Ambiguous {
public static void main(String[] args) {
System.out.println(PI); // compile error: reference to PI is ambiguous
}
}The error appears only at the point of use. Having the two imports is legal. For methods, the compiler gathers the imported overloads from both classes and tries overload resolution. If two candidates have identical signatures, as with sqrt(double) here, the call is ambiguous. If the signatures differ, the combined set works like any overloaded method.
Common errors
- Forgetting
static.import java.lang.Math.max;fails becauseMath.maxis not a type. Writeimport static java.lang.Math.max;. - Importing an instance member. Only static members can be imported.
- Expecting a wildcard to import types and members together.
import static pkg.Type.*;imports static members ofType, including its static nested types. It does not import other classes in the packagepkg. For that you needimport pkg.*;. - Wildcard imports hiding the source. With
import static app.Constants.*;a reader seesTIMEOUTand cannot tell which class defines it without using the IDE. If you add a name toConstantslater, it may clash with a name you already import elsewhere. - Shadowing surprises. A newly added local method can silently take over a call that used to resolve to the import, or break it with a "no suitable method" error, as described above.
- Importing generic names. Importing
of,get,createormaxfrom several classes makes the code ambiguous for people even when the compiler accepts it.
Guidelines for choosing
The Java documentation recommends using static imports very sparingly. Overuse makes code harder to read because the reader cannot tell which class a member comes from. These rules of thumb follow from the behavior above:
- Prefer single-static-imports to wildcards, so each name has a visible origin.
- Import names that are distinctive and widely recognized, such as
assertEquals,toList,PIand enum constants. Avoid generic names likeof,getandmaxwhen more than one imported class could supply them. - Use static imports where one class's members appear many times in a file, such as test classes, math-heavy code and stream pipelines.
- Keep the prefix when a call appears once or twice.
Collections.emptyList()costs nothing and documents itself. - Use a static import instead of a constant interface, never in addition to one.
Exercise
A class imports import static java.lang.Math.max; and also declares its own method static int max(int a, int b, int c). Inside that class, the code calls max(4, 9). Does it compile? Why or why not?
Show answer
No. A method declared in the class hides all statically imported methods with the same name, regardless of signature. Inside the class, only the three-argument max is visible, so max(4, 9) has no applicable method. Calling Math.max(4, 9) with the class prefix fixes it.
Exercise
A file has import static java.lang.Math.*; and import static java.lang.StrictMath.*;. It contains double r = PI;. What happens, and what is the smallest change that fixes it without removing either import?
Show answer
It fails to compile with "reference to PI is ambiguous", because both classes supply a static field named PI through on-demand imports. Adding the single-static-import import static java.lang.Math.PI; fixes it, because a single-static-import takes priority over on-demand imports. Writing Math.PI also works.
Exercise
True or false: import static java.util.Map.Entry; is invalid because Entry is a type, not a static method or field. Explain.
Show answer
False. Static nested types are static members of the enclosing type, so they can be imported with a static import. import java.util.Map.Entry; works equally well for a nested type.