the field no longer refers to it. This approach also covers the case of inner class objectsan inner class instance
is reachable whenever its enclosing instance is reachable.
There are further subtle interactions between finalization, synchronization, and the memory model, but these
are advanced topics unneeded by most programmers and are beyond the scope of this book.
Don't ever take a fence down until you know the reason why it was put up.
G.K. Chesterton
Chapter 18. Packages
For some reason a glaze passes over people's faces when you say "Canada". Maybe we should
invade South Dakota or something.
Sandra Gotlieb, wife of Canadian ambassador to U.S. (19811989)
Packages define units of software that can be distributed independently and combined with other packages to
form applications. Packages have members that are related classes, interfaces, and subpackages, and may
contain additional resource files (such as images) used by the classes in the package. Packages are useful for
several reasons:
Packages create groupings for related interfaces and classes. For example, a set of library classes for
performing statistical analysis could be grouped together in a stats package. The package can be
placed in an archive file, together with a manifest describing the package, and shipped to customers
for use in their applications.
•
Packages create namespaces that help avoid naming conflicts between types. Interfaces and classes in
a package can use popular public names (such as List and Constants) that make sense in one
context but might conflict with the same name in another package.
•
Packages provide a protection domain for developing application frameworks. Code within a package
can cooperate using access to identifiers that are unavailable to external code.
•
Let us look at a package for the attribute classes you saw in previous chapters. We will name the package
attr. Each source file whose classes and interfaces belong in the attr package states its membership with
its package declaration:
package attr;
This statement declares that all classes and interfaces defined in this source file are part of the attr package.
A package declaration must appear first in your source file, before any class or interface declarations. Only
one package declaration can appear in a source file. The package name is implicitly prefixed to each type
name contained within the package.
If a type is not declared as being part of an explicit package, it is placed in an unnamed package. Each system
must support at least one unnamed package, but they can support moretypically one per class loader. The
existence of the unnamed package makes it simple for you to write small programs without being encumbered
by the organizational requirements imposed on the members of named packages. Any non-trivial program or
set of library classes should always be part of a named package.