Datasheet
This mechanism also prevents the dangerous coding practice of placing a set of static attributes into an
interface, and then in each class that needs to use the attributes, implementing that interface. The follow-
ing interface should not be implemented in order to use the attributes without qualification:
interface ShapeNumbers {
public static int CIRCLE = 0;
public static int SQUARE = 1;
public static int TRIANGLE = 2;
}
Implementing this interface creates an unnecessary dependence on the ShapeNumbers interface. Even
worse, it becomes awkward to maintain as the class evolves, especially if other classes need access to
these constants also and implement this interface. It is easy for compiled classes to get out of synchro-
nization with each other if the interface containing these attributes changes and only some classes are
recompiled.
To make this cleaner, the static members are placed into a class (instead of an interface) and then
imported via a modified syntax of the import directive.
ShapeNumbers is revised to the following:
package MyConstants;
class ShapeNumbers {
public static int CIRCLE = 0;
public static int SQUARE = 1;
public static int TRIANGLE = 2;
}
A client class then imports the static information from the ShapeNumbers class and can then use the
attributes
CIRCLE, SQUARE, and TRIANGLE without the need to prefix them with ShapeNumbers and the
member operator.
To import the static members in your class, specify the following in the import section of your Java
source file (at the top):
import static MyConstants.ShapeNumbers.*; // imports all static data
This syntax is only slightly modified from the standard format of the import statement. The keyword
static is added after the import keyword, and instead of importing packages, you now always add on
the class name because the static information is being imported from a specific class. The chief reason the
keyword
static is added to the import statement is to make it clear to those reading the source code
that the import is for the static information.
You can also import constants individually by using the following syntax:
import static MyConstants.ShapeNumbers.CIRCLE;
import static MyConstants.ShapeNumbers.SQUARE;
This syntax is also what you would expect. The keyword static is included because this is a static
import, and the pieces of static information to import are each specified explicitly.
22
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 22