Java Reference
In-Depth Information
alternativethatletsyouavoidhavingtospecifypackagedetails.Thisalternativeisthe
import statement.
Theimportstatementimportstypesfromapackagebytellingthecompilerwhereto
lookforunqualifiedtypenamesduringcompilation.Thisstatementconsistsofreserved
word
import
, followed by a member access operator-separated list of package and
subpackage names, followed by a type name or
*
(asterisk), followed by a semicolon.
The
*
symbolisawildcardthatrepresentsallunqualifiedtypenames.Ittellsthecom-
pilertolookforsuchnamesintheimportstatement'sspecifiedpackage,unlessthetype
name is found in a previously searched package. (Using the wildcard does not have a
performance penalty or lead to code bloat, but can lead to name conflicts, as you will
see.)
Forexample,
import ca.tutortutor.graphics.shapes.Circle;
tells
the compiler that an unqualified
Circle
class exists in the
ca.tutortutor.graphics.shapes
package. Similarly,
import
ca.tutortutor.graphics.shapes.*;
tells the compiler tolookinthis pack-
age if it encounters a
Rectangle
class, a
Triangle
class, or even an
Employee
class (if
Employee
has not already been found).
Tip
Youshouldavoidusingthe
*
wildcardsothatotherdeveloperscaneasilysee
which types are used in source code.
BecauseJavaiscasesensitive,packageandsubpackagenamesspecifiedinanimport
statement must be expressed in the same case as that used in the package statement.
When import statements are present in source code, only a package statement and
comments can precede them.
Caution
Placinganythingotherthanapackagestatement,importstatements,static
importstatements(discussedshortly),andcommentsaboveanimportstatementcauses
the compiler to report an error.
You can run into name conflicts when using the wildcard version of the import
statement because any unqualified type name matches the wildcard. For example, you
have
graphics.shapes
and
geometry
packages that each contain a
Circle
class, the source code begins with
import geometry.*;
and
import graph-
ics.shape.*;
statements, and it also contains an unqualified occurrence of
Circle
. Because the compiler does not know if
Circle
refers to
geometry
's
Circle
classor
graphics.shape
's
Circle
class,itreportsanerror.Youcanfix
this problem by qualifying
Circle
with the correct package name.