Background:
Static import was introduced in Java 5 (JDK 1.5) to improve code readability and reduce verbosity. Before the introduction of this mechanism, to use static members of another class, one always had to write the full class name, making the code cumbersome and less clean.
Problem:
Often, it is necessary to repeatedly refer to static methods or fields within the same class (for example, mathematical functions or constants). Constantly mentioning the class name hampers readability and increases the amount of code.
Solution:
The static import mechanism allows importing static members of a class (methods or fields) directly, so they can be accessed without the class name prefix. This simplifies the code and makes it more compact, especially when extensively using libraries like Math.
Example code:
import static java.lang.Math.*; public class StaticImportExample { public static void main(String[] args) { double x = cos(PI * 2); double y = pow(2, 4); System.out.println(x + ", " + y); } }
Key features:
Can all static members of a class be imported using a wildcard (Wildcard Static Import)?
Yes, it can. The expression import static java.lang.Math.*; imports all static methods and fields of that class. However, this reduces readability and may cause name conflicts if such conflicts exist in other imported classes.
Can static members of a non-existent class be imported?
No, the compiler will throw an error. For example,
import static java.util.List.NONEXISTENT_FIELD; // Compilation error
Does static import work for non-static members of a class?
No. Static import applies only to static methods and fields. Attempting to import non-static members will result in a compilation error.
*) reduces readability and leads to name conflictsA programmer on the team uses import static java.lang.Math.*; and import static java.util.Collections.*;, not paying attention to name overlaps. As a result, it becomes difficult to understand which specific method or constant is used in each specific location, and when new libraries appear — name conflicts are possible.
Pros:
Cons:
A developer imports only the necessary methods from Math, for example,
import static java.lang.Math.PI; import static java.lang.Math.cos;
The entire project remains understandable and maintainable, and the statically imported members are easy to track.
Pros:
Cons: