Java Reference
In-Depth Information
Creating a Package
Problem
You want to be able to import classes and/or organize your classes, so you want to create
your own package.
Solution
Put a
package
statement at the front of each file, and recompile with
-d
or a build tool or
IDE.
Discussion
The
package
statement must be the very first noncomment statement in your Java source
file—preceding even
import
statements—and it must give the full name of the package.
Package names are expected to start with your domain name backward; for example, my In-
ternet domain is
darwinsys.com
, so most of my packages begin with
com.darwinsys
and a
project name. The utility classes used in this topic and meant for reuse are in one of the
com.darwinsys
packages listed in
Downloading and Using the Code Examples
,
and each
source file begins with a statement, such as:
package com.darwinsys.util;
The demonstration classes in the
JavaSrc
repository do not follow this pattern; they are in
packages with names related to the chapter they are in or the
java.*
package they relate to;
for example,
lang
for basic Java stuff,
structure
for examples from the data structuring
that you will put them in a “real” package if you reuse them in your application!
Once you have package statements in place, be aware that the Java runtime, and even the
compiler, will expect the compiled
.class
files to be found in their rightful place (i.e., in the
subdirectory corresponding to the full name somewhere in your CLASSPATH settings). For
example, the class file for
com.darwinsys.util.FileIO
must
not
be in the file
FileIO.class
in my CLASSPATH but must be in
com/darwinsys/util/FileIO.class
relative to one of the dir-
ectories or archives in my CLASSPATH. Accordingly, if you are compiling with the
command-line compiler, it is customary (almost mandatory) to use the
-d
command-line ar-