6.7 Packages | 295
a semicolon. By convention, Java programmers start a package identifier with a lowercase let-
ter to distinguish it from class identifiers.
packagesomeName;
Next, we can write our import declarations and then one or more class declarations.
Java calls this a compilation unit.Its syntax diagram is shown here:
As you can see from the syntax diagram, we can write a series of class declarations follow-
ing the import declarations. These classes are members of the package. All of the package
members (the classes) have access to each other’s nonprivate members. We say “nonpri-
vate” because, in addition to using the keywords publicor privatewith fields and methods,
we can write member declarations without any modifiers. When we do so, then the field or
method is neither publicnor private, but rather it is something in between—it can be accessed
by any member of the package.
When we usepublic, then a field or method can be used outside of the class and by any class
that imports its package. When we useprivate, then the field or method can be accessed only
within the class itself. When we use neither, the field or method can be used within the class
and within other classes in the same package, but not by classes outside of the package. As an
analogy, you can think of packages as being like a family. Some things are yours alone (private),
some things you share with your family (package), and some things anyone can use (public).
Classes that are imported into the package can be used by any of the classes declared
in the package. From the perspective of the imported classes, the declared classes are user
code and thus can access only their publicmembers. Note that imported classes are not
members of the package. You can think of an imported package as a guest in your house. Your
guest may share some things (public) with your family, but the things that you share only with
your family are not shared with the guest, and the things that the guest shares only with his
or her family aren’t shared with you.
Although we can declare multiple classes in a compilation unit, only one class can be de-
claredpublic. The others must have package-level access; that is, they are written without
an access modifier. If a compilation unit can hold at most onepublicclass, how do we cre-
ate packages with multiplepublicclasses? We use multiple compilation units, as we de-
scribe next.
package Identifier;
Class
Import-Declaration
Compilation-Unit
...
...