Search

Static Import in Java

Static Import is a new feature added in Java 5 specification.
Static import in Java allows to import static members of class and use them, as they are declared in the same class, means access any static member of class directly without using class name.

Example:


import static java.lang.System.*;
public class Main{
 public static void main(String args[]){
  out.println("Testig Static Import");// no need to use System.out.println();
 }
}



Advantage of static import:
Main advantage of using static import in Java is saving keystrokes. If you are frequently usingSystem.out.println() statements, you can static import System.out or System.* and type out.println() or println() in your code.

Disadvantage of static import:
If you overuse of the static import feature, it makes the program unreadable and unmaintainable. Static import has another disadvantage in terms of conflicts, once you use static import Integer.MAX_VALUE than after you can not use MAX_VALUE as variable or constants in you code.

Summary:
Finally few points must remembering about static import in Java :

1) Static import statements are written as "import static" in code and not "static import".

2) If you import two static fields with same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile time error. But if other static modifier is not imported explicitly e.g. you have imported java.lang.Long.*, MAX_VALUE will refer to Integer.MAX_VALUE.

3) Static import doesn't improve readability as expected, as many Java programmers prefer Integer.MAX_VALUE which is clear that which MAX_VALUE you are referring.

4) You can apply static import statement not only on static fields but also on static methods in Java.

No comments:

Post a Comment