Java Reference
In-Depth Information
Defining a Package
All classes in Java belong to some package. When no package statement is specified, the
default (global) package is used. Furthermore, the default package has no name, which
makes the default package transparent. This is why you haven't had to worry about pack-
ages before now. While the default package is fine for short, sample programs, it is inad-
equate for real applications. Most of the time, you will define one or more packages for
your code.
To create a package, put a package command at the top of a Java source file. The classes
declared within that file will then belong to the specified package. Since a package defines
a namespace, the names of the classes that you put into the file become part of that pack-
age's namespace.
This is the general form of the package statement:
package pkg ;
Here, pkg is the name of the package. For example, the following statement creates a pack-
age called mypack :
Java uses the file system to manage packages, with each package stored in its own dir-
ectory. For example, the .class files for any classes you declare to be part of mypack must
be stored in a directory called mypack .
Like the rest of Java, package names are case sensitive. This means that the directory
in which a package is stored must be precisely the same as the package name. If you have
trouble trying the examples in this chapter, remember to check your package and directory
names carefully. Lowercase is often used for package names.
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not exclude
other classes in other files from being part of that same package. Most real-world packages
are spread across many files.
You can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package state-
ment is shown here:
package pack1.pack2.pack3…packN ;
Of course, you must create directories that support the package hierarchy that you create.
For example,
Search WWH ::




Custom Search