static import in java

static import allows access to static members without qualification.

Lets start with an example
 
package test;

public class Test{
 public static String s_var = "example";
 
 public static void sMethod(){
  System.out.println("welcome to sMethod");
 }
}
Before Java 1.5, In order to access static members(s_var and sMethod), it is necessary to qualify references with the class they came from. like
 
import test.Test;
public class StaticImportDemo {

 public static void main(String[] args) {
  System.out.println(Test.s_var);
  Test.sMethod();
 }

}
In Java 1.5, Introduced static import - it allows access to static members without qualification. Means you can access static members directly(without class name). you can import individually
 
import static test.Test.s_var;
import static test.Test.sMethod;;

public class StaticImportDemo {

 public static void main(String[] args) {
  System.out.println(s_var);
  sMethod();
 }

}
or import all at a time
 
import static test.Test.*;
public class StaticImportDemo {

 public static void main(String[] args) {
  System.out.println(s_var);
  sMethod();
 }

}
Note : It's not advisable to use this feature, because over a period you may not understand which static method or static attribute belongs to which class inside the java program. The program may become unreadable.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...