Java Reference
In-Depth Information
Let's look at another example of using static import declarations. The
Math
class in the
java.lang
package has
many utility constants and static methods. For example, it has a class variable named
PI
, whose value is equal to
22/7
(the pi in mathematics). If you want to use any of the static variables or methods of the
Math
class, you will need to
qualify them with the class name
Math
. For example, you would refer to the
PI static
variable as
Math.PI
and the
sqrt()
method as
Math.sqrt()
. You can import all static members of the
Math
class using the following static-import-
on-demand declaration:
import static java.lang.Math.*;
Now you can use the name of the static member without qualifying them with the class name
Math
. Listing 6-6
demonstrates using the
Math
class by importing its
static
members.
Listing 6-6.
Using Static Imports to Import Multiple Static Members of a Type
// StaticImportTest2.java
package com.jdojo.cls;
import static java.lang.System.out;
import static java.lang.Math.*;
public class StaticImportTest2 {
public static void main(String[] args) {
double radius = 2.9;
double area = PI * radius * radius;
out.println("Value of PI is: " + PI);
out.println("Radius of circle: " + radius);
out.println("Area of circle: " + area);
out.println("Square root of 2.0: " + sqrt(2.0));
}
}
Value of PI is: 3.141592653589793
Radius of circle: 2.9
Area of circle: 26.420794216690158
Square root of 2.0: 1.4142135623730951
The following are some important rules about static import declaration.
Static Import Rule #1
If two static members with the same simple name are imported, one using single-static import declaration
and other using static-import-on-demand declaration, the one imported using single-static import declaration
takes precedence. Suppose there are two classes,
p1.C1
and
p2.C2
. Both classes have a static method called
m1
. The
following code will use
p1.C1.m1()
method because it is imported using the single-static import declaration:
// Test.java
package com.jdojo.cls;
import static p1.C1.m1; // Imports C1.m1() method
import static p2.C2.*; // Imports C2.m1() method too