Sunday, June 30, 2013

Java Static Import Example

Static Import Example

Static import java is the great feature, which is available in Java 1.5.

Before static import came into picture, the developer needs to access the members through

class name.

For Example : ClassName.methodName();

                     ClassName.dataMember;

But with static imports you just import the members in the import section of the class, i.e

import static members at the top of the class, after package statement and before declaring

class.

If the class is too big and you are importing too many members using static import concept

it is unnecessary confusion for the developer. so you should use the static imports wherever

you require which are suitable to implement in the application. Don't import unnecessary static imports

which you are not using in that application.

Static import syntax :

import static package.className.member;

If suppose two variables/methods are same in two classes, you are importing them in the same

class, you will get compilation error.

The import <pkg.className.member> collides with another import statement.

Sample code for static import Example :


 package javademos.staticimport.example;  
 public class CommonHelper {  
      public final static int MAX_HEIGHT = 11;  
      public final static int MAX_AGE = 100;  
      public static int countTokens(String str) {  
           String[] strArray = null;  
           strArray = str != null ? str.split(",") : null;  
           return strArray != null ? strArray.length : 0;  
      }  
 }  



 package javademos.staticimport.example;  
 //import static members at the top of the class.  
 //import static data members  
 import static javademos.staticimport.example.CommonHelper.MAX_AGE;  
 import static javademos.staticimport.example.CommonHelper.MAX_HEIGHT;  
 //import static methods  
 import static javademos.staticimport.example.CommonHelper.countTokens;  
 /**  
  * java static import example  
  * Static import is very much useful while developing the applicatins.  
  * You just import the members you require at the top of the class and  
  * use in your application directly.  
  *   
  */  
 public class MainClass {  
      public static void main(String[] args) {  
           System.out.println("Person Max Age : " +MAX_AGE);  
           System.out.println("Person Max Height : " +MAX_HEIGHT);  
           System.out.println("No of tokens : "+countTokens("a,b,c"));  
      }  
 }  

Output of the Code :

Person Max Age100
Person Max Height11
3



0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.