Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Some types define static constants or methods that are useful to other types. For example, thejava.lang.Math
class defines thePI
constant and thecos
method: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 import construct. This construct, similar to a normal
import
, 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;Once the class has been imported, the objects can be used without qualification. For example, the previous code snippet would become:import static java.lang.Math.*;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 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.