Java Reference
In-Depth Information
static void showDirection(int dir)
{
switch (dir)
{
case NORTH: System.out.println("Moving north");
break;
case SOUTH: System.out.println("Moving south");
break;
case EAST : System.out.println("Moving east");
break;
case WEST : System.out.println("Moving west");
}
}
}
of not having to specify
Directions.NORTH
,
Directions.SOUTH
,
Direc-
tions.EAST
, and
Directions.WEST
.
This is an appalling misuse of an interface. These constants are nothing more than
animplementationdetailthatshouldnotbeallowedtoleakintotheclass'sexported
in-
terface
,becausetheymightconfusetheclass'susers(whatisthepurposeofthesecon-
stants?).Also,theyrepresentafuturecommitment:evenwhentheclassnolongeruses
these constants, the interface must remain to ensure binary compatibility.
Java5introducedanalternativethatsatisfiesthedesireforconstantinterfaceswhile
avoiding their problems. This static imports feature lets you import a class's
static
memberssothatyoudonothavetoqualifythemwiththeirclassnames.Itisimplemen-
ted via a small modification to the import statement, as follows:
import static
packagespec
.
classname
. (
staticmembername
| * );
Thestaticimportstatementspecifies
static
after
import
.Itthenspecifiesamem-
beraccessoperator-separatedlistofpackageandsubpackagenames,whichisfollowed
bythememberaccessoperatorandaclass'sname.Onceagain,thememberaccessop-
erator is specified, followed by a single static member name or the asterisk wildcard.
Caution
Placing anything apart from a package statement, import/static import
statements,andcommentsaboveastaticimportstatementcausesthecompilertoreport
an error.