Printable Version Printable Version

Java Static Import

Apr 30th, 2009 | By admin | Category: Java

This tutorial gives an idea on a feature introduced in Java 5 , Static Import . In order to access static member of a class ,it is recomended to qualify the references by the class they belongs to.
For an example ,

Math.sqrt(Math.pow(45, 2));

– here sqrt and pow are the static methods of the class Math.
A static import allows unqualified access to static member of a class.We should not keep any static member in an interface and then inherit from that rather it is a better idea to import them to a new class.
Static import can be achieved in two ways,
1. Single static import – Import a particular static member of a class.

import static packageName.ClassName.staticMemberName;

For an example , if you want to access Math class’s static member sqrt and pow the import should be,

import static java.lang.Math.sqrt;
import static java.lang.Math.pow;

2. Static import on demand – Import all static member of a class.

import static packageName.ClassName.*;

In this case the import should be import static

java.lang.Math.*

Have look at the following codes :

This is a class with Static methods :

package com.etechguide.java.feature;
public class ClassWithStaticMembers {
public static void talk(){
System.out.println("I am talking");
}
public static void walk(){
System.out.println("I am walking");
}
}

This is a class with Static veriables :

package com.etechguide.java.feature;
public class ClassWithStaticVers {
public static String fruit = "Apple";
public static String name = "Anthony";
public static String state = "green";
}

This class is making use of the static import

package com.etechguide.java.feature;
import static com.etechguide.java.feature.ClassWithStaticMembers.talk;
import static com.etechguide.java.feature.ClassWithStaticVers.*;
public class StaticImport {
public static void main(String[] args) {
talk(); // A static method from the class ClassWithStaticMembers in the package
// com.etechguide.java.feature
// Walk(); This also a staic method of the class ClassWithStaticMembers but not
// accessible as we have not imported it. To access this method ,
ClassWithStaticMembers.walk();

//Here accessing all the static variables of the class  ClassWithStaticVers

System.out.println(name + " loves " + state +" "+ fruit);

}
}
  • Share/Save/Bookmark
Tags: ,

Leave Comment