August 9, 2011

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

//If all the members are static
import  static packageName.className.*;
//To import one static method
import  static packageName.className.MethodName;

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

package in.bibek;
public class TestStaticImports {
	public static void main(String[] args) {
		System.out.println("Static Import");

After Static imports

package in.bibek;
import static java.lang.System.out;
import static java.lang.Thread.MAX_PRIORITY;

public class TestStaticImports {
	public static void main(String[] args) {
		out.println("Static Import");

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.

You may also like...

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.

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