In this version, the names sqrt and pow are brought into view by these static import
statements:
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
After these statements, it is no longer necessary to qualify sqrt( ) or pow( ) with their class name.
Therefore, the hypotenuse calculation can more conveniently be specified, as shown here:
hypot = sqrt(pow(side1, 2) + pow(side2, 2));
As you can see, this form is considerably more readable.
There are two general forms of the import static statement. The first, which is used by
the preceding example, brings into view a single name. Its general form is shown here:
import static pkg.type-name.static-member-name;
Here, type-name is the name of a class or interface that contains the desired static member. Its full
package name is specified by pkg. The name of the member is specified by static-member-name.
The second form of static import imports all static members of a given class or interface.
Its general form is shown here:
import static pkg.type-name.*;
If you will be using many static methods or fields defined by a class, then this form lets you
bring them into view without having to specify each individually. Therefore, the preceding
program could have used this single import statement to bring both pow( ) and sqrt( ) (and
all other static members of Math) into view:
import static java.lang.Math.*;
Of course, static import is not limited just to the Math class or just to methods. For example,
this brings the static field System.out into view:
import static java.lang.System.out;
After this statement, you can output to the console without having to qualify out with
System, as shown here:
out.println("After importing System.out, you can use out directly.");
Whether importing System.out as just shown is a good idea is subject to debate. Although
it does shorten the statement, it is no longer instantly clear to anyone reading the program
that the out being referred to is System.out.
One other point: in addition to importing the static members of classes and interfaces
defined by the Java API, you can also use static import to import the static members of classes
and interfaces that you create.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home