Static Imports

Static Imports

We have been using lots of import statement in our code. The only value import statement have is that they save typing and improves the code readability. With Java 5 import statement was enhanced to provide even greater keystroke-reduction capabilities and this is called static import. This can be used when we want to use a class’s static members.

How to Use

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

Example : Before static imports

After Static imports

Key Points to Remember while using static imports

  • We must say this as import static not static import.
  • Watch out for ambiguously named static members. For example if we do a static import for both the Integer class and the Long class, referring to MAX_VALUE will cause a compiler error, since both Integer and Long have a MAX_VALUE constant, and Java won’t know which MAX_VALUE you’re referring to.
  • We can have static import on static object references, constants (static+final) and static methods.

In few cases use or static imports makes the code little harder to read. So its upto the developer how and where to use.
Ref

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.