|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Some classes define static constants or methods that are useful to other classes. For example, thejava.lang.Mathclass defines thePIconstant and thecosmethod:Ordinarily, to use these objects from another class, you prefix the class name:public static final double PI 3.141592653589793 public static double cos(double a)Prefixing the class name over and over can result in cluttered code. To avoid this programmers sometimes put static objects into an interface and inherit from that interface. This practice, called the Constant Interface Antipattern, is not recommended. (You can find more information on the Constant Interface Antipattern in the book Effective Java by Joshua Bloch.) This is considered bad Java programming practice because when a class implements an interface, it becomes part of the class's public API. Implementation details, such as using the static members of another class, should not leak into public APIs.double r = Math.cos(Math.PI * theta);Release 5.0 introduced another solution for this situation: the
static importconstruct. This construct, similar to a normalimport, allows unqualified access to static objects without inheriting from the type containing the static objects. (For more information on a standardimport, see Using Package Members.) The objects can be imported either individually:
or as a group:import static java.lang.Math.PI;//Enable direct access to PI. import static java.lang.Math.*;Once the class has been imported, the objects can be used without qualification. For example, the previous code snippet would become:
Note: List the members accessed from a particular package in the comment for the import. This enables the programmer maintaining the code (which might be you) to determine where a particular constant or method is defined.double r = cos(PI * theta);
Note: Use static import very sparingly, if at all. It's useful for situations when you need frequent access to a few static objects from one or two classes. Overusing static import can result in code that is difficult to read and maintain, since readers of the code won't know which class defines a particular static object. Used properly, it makes code more readable by removing the boilerplate repetition of class names.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.