Static Import in Java

With Java static import feature, which was added in Java 5, you can access static members (fields and methods defined as public static) of a class without qualifying them with class name.

How to use static import in Java

Generally if you need to access any static member (static field or method) of a class you need to qualify it with the class name.

For example syntax for accessing a static method-

Static import helps with shortening the syntax required to use a static member. Using static import you can import static member that is needed in the class.
Syntax for static import of static field

Syntax for static import of static method

You can also import all the static members of a class using the following syntax-

Java static import example

Math class in Java has many static methods, first let’s see how we can use those static methods if static import is not used.

Output

Example using static import
By using static import you don’t need to qualify methods with class name.

As you can see in the code static import is done for all the static members of the Math class so there is no need to qualify methods of the Math class.

You could have also just imported the required methods.

Advantages of using static import

  1. If you are using static members from a class or two with in your code then static import helps in making the code concise.
  2. Static import also helps you to avoid creating an interface having only constants and then implementing that interface which is considered a constant interface anti pattern. You can as well define static fields with in a class and then do a static import of static members of that class.

Drawbacks of using static import

  1. If you are doing static import from lots of classes then it creates confusion as it is hard to know which class any particular static member belong to.
  2. Static import may also cause ambiguity if two static members of the same name are imported from different classes.

Static import ambiguity

If two static members of the same name are imported from different classes then compiler won’t be able to decide which one to use and throw an error.

For example consider the following code where static members of both Integer and Long are imported using static import. Now using the static method valueOf(String) and static field MAX_VALUE results in ambiguity as these members are present in both of the classes.

static import in Java

That’s all for the topic Static Import in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.