Java Reference
In-Depth Information
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. 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:
Of course, static import is not limited just to the Math class or just to methods. For ex-
ample, this brings the static field System.out into view:
After this statement, you can output to the console without having to qualify out with Sys-
tem , as shown here:
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 .
As convenient as static import can be, it is important not to abuse it. Remember, one
reason that Java organizes its libraries into packages is to avoid namespace collisions.
When you import static members, you are bringing those members into the global
namespace. Thus, you are increasing the potential for namespace conflicts and the inadvert-
ent hiding of other names. If you are using a static member once or twice in the program,
it's best not to import it. Also, some static names, such as System.out , are so recognizable
that you might not want to import them. Static import is designed for those situations in
which you are using a static member repeatedly, such as when performing a series of math-
ematical computations. In essence, you should use, but not abuse, this feature.
Search WWH ::




Custom Search