The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Interfaces and Packages

The "Static Import" Construct

Some classes define static constants or methods that are useful to other classes. For example, the java.lang.Math class defines the PI constant and the cos method:
public static final double PI 3.141592653589793
public static double cos(double a)
Ordinarily, to use these objects from another class, you prefix the class name:
double r = Math.cos(Math.PI * theta);
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.

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 standard import, see Using Package Members (in the Learning the Java Language trail).) The objects can be imported either individually:

import static java.lang.Math.PI;
or as a group:
//Enable direct access to PI.
import static java.lang.Math.*;

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.
Once the class has been imported, the objects can be used without qualification. For example, the previous code snippet would become:
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.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.