This tutorial explains the concept of static imports introduced in Java 1.5 with examples. It starts with defining static imports, followed by code snippets showing examples of coding static methods and member variables with static imports and the earlier style of coding without static imports. Motivation for the static imports feature is explained next, followed by the advantages and disdavantages of using this feature.
What are Static Imports
Static Imports allow accessing the static attributes (variables & methods) of a class without using the <ClassName> prefix. In other words, static imports allow unqualified access to static members of a class.
Examples of using Static Imports
- Using a static member method
- Using a static member variable
Important Note – If you use two static imports from different classes with the same name(
Float.MIN_VALUE as just
MIN_VALUE) then compiler will throw an error as it will not be able to decide which class’s static member
MIN_VALUE is being referred in an unqualified way.
Motivation(Cause) for using Static Imports
Prior to the arrival of static imports, programmer used to get around the problem of qualifying static members with the class name by making these static variables a part of a higher level interface. They would then implement this interface to get unqualified access to the static members.
The above way of using static values from a higher-level interface is actually an anti-pattern called Constant Interface Antipattern. The problem with this approach is that if we include any variable in the higher level interface then it inherently becomes a part of the API which is exposed using that interface. This is uncalled for and not the actual purpose of putting the static values in the interface and should be avoided.
Advantages of Using Static Imports
- Reduces actual coding as the prefix need not be mentioned each time
- For a large class and/or multiple uses of the same static member of a class it helps by shortening the reference to that member
Disadvantages of Using Static Imports
- Code readability, and hence maintainability, takes a hit. Non-creator of the class could get confused if he\she does not refer imports at the top and might waste time in searching for a local member of the same name as the member is now unqualified.
- Sometimes programmers tend to import all the static members of a class using an asterik(*) at the end of their static import statements. This brings down the readability of the code drastically and should be avoided.
Static imports should be used to reduce the amount of code being written but at the same time they should be used with care as code readability and maintainability takes a hit because of them.