Java Reference
In-Depth Information
An example of how the
package
statement is used is shown in Figure 3.16,
where we move the
BigRational
class to a new package,
weiss.math
.
3.8.3
the
CLASSPATH
environment variable
Packages are searched for in locations that are named in the
CLASSPATH
vari-
able. What does this mean? Here are possible settings for
CLASSPATH
, first for a
Windows system and second for a Unix system:
The
CLASSPATH
vari-
able specifies files
and directories that
should be searched
to find classes.
SET CLASSPATH=.;C:\bookcode\
setenv CLASSPATH .:$HOME/bookcode/
In both cases, the
CLASSPATH
variable lists directories (or jar files
2
) that
contain the package's class files. For instance, if your
CLASSPATH
is corrupted,
you will not be able to run even the most trivial program because the current
directory will not be found.
A class in package
p
must be in a directory
p
that will be found by
searching through the
CLASSPATH
list; each
.
in the package name repre-
sents a subdirectory. Starting with Java 1.2, the current directory (directory
.
)
is always scanned if
CLASSPATH
is not set at all, so if you are working
from a single main directory, you can simply create subdirectories in it
and not set
CLASSPATH
. Most likely, however, you'll want to create a sep-
arate Java subdirectory and then create package subdirectories in
there. You would then augment the
CLASSPATH
variable to include
.
and
the Java subdirectory. This was done in the previous Unix declaration
when we added
$HOME/bookcode/
to the
CLASSPATH
. Inside the
bookcode
direc-
tory, you create a subdirectory named
weiss
, and in that subdirectory,
math
,
util
and
nonstandard
. In the
math
subdirectory, you place the code for the
BigRational
class.
An application, written in any directory at all, can then use the
BigRational
class either by its full name
A class in package
p
must be in a
directory
p
that will
be found by
searching through
the
CLASSPATH
list.
weiss.math.BigRational;
or simply using
BigRational
, if an appropriate
import
directive is provided.
Moving a class from one package to another can be tedious because it
may involve revising a sequence of
import
directives. Many development tools
will do this automatically, as one of the options for
refactoring
.
2. A
jar
file is basically a compressed archive (like a zip file) with extra files containing Java-
specific information. The
jar
tool, supplied with the JDK, can be used to create and expand
jar files.
Search WWH ::
Custom Search