static import
static import is one of the new features added in J2SE 5 , which expands the capabilities of the import keyword.
By using static import it is possible to refer to static members directly by their names.We don’t have to qualify them with the class name.This in turn simplifies and shorten the syntax used to refer static member of a class.
Lets understand the use of static import with an example program to find hypotenuse of a right triangle. We know that the formula to find hypotenuse of a right triangle is sqrt(a2+b2), if a and b are the sides of the triangle.
Without using static import:
1 2 3 4 5 6 7 8 9 |
public class StaticImportDemo { public static void main(String[] args) { double side1=10; double side2=12; double hypotenus; hypotenus=Math.sqrt(Math.pow(side1, 2)+Math.pow(side2,2)); System.out.println("hypotenus is "+hypotenus); } } |
By using static import:
1 2 3 4 5 6 7 8 9 10 11 12 |
import static java.lang.Math.sqrt; import static java.lang.Math.pow; public class StaticImport { public static void main(String[] args) { double side1 = 10; double side2 = 12; double hypotenus; hypotenus = sqrt(pow(side1, 2) + pow(side2, 2)); System.out.println("hypotenus is " + hypotenus); } } |
Benefits of using static import
- We don’t have to qualify the static method with the class name.
- The code is considerably more readable.
Two different forms of the import static statement.
- import static package.typeName.staticMemeberName
Ex: import static java.lang.math.sqrt;
2. import static package.typeName.*
Ex: import static java.lang.math.*;
In this case, all the static methods and fields in a class are imported. in our above example , sqrt,pow etc
Another example of static import
1 2 3 4 5 6 7 |
import static java.lang.System.out; public class OutMethodDemo { public static void main(String[] args) { out.println("This is from j2eereference.com"); } } |
output
This is from j2eereference.com
dexterous.gal@gmail.com says
July 20, 2012 at 3:45 pmIf there are same names and return types for static methods in two different classes and we have done a static import for both then how is it resolved?Is it done based on order of import?
bs.mohankumar@gmail.com says
July 20, 2012 at 4:16 pmThis will give the below compilation error while invoking the method:
The method method1() is ambiguous for the type Static3
Please refer the example for more:
package test;
public class Static1 {
public static void method1(){
System.out.println(“Mohan Static-1”);
}
public static void main(String[] args){
}
}
package test;
public class Static2 {
public static void method1(){
System.out.println(“Mohan Static-2”);
}
public static void main(String[] args){
}
}
import static test.Static1.method1;
import static test.Static2.method1;
public class Static3 {
public static void main(String[] args){
method1();
}
}
Hope this has answered 🙂
Thanks,
Mohan
dexterous.gal@gmail.com says
July 26, 2012 at 3:20 pmThanx mohan my doubt is cleared.