Java Reference
In-Depth Information
3.3
U
SING
(
AND
M
AKING
) J
AVA
API
S
With every class you write, you define a name—the name of the class. But what
if someone else has already used that name? Java programming should encour-
age reuse of existing code, so how do you keep straight which names are
available?
This is a
namespace
issue—who can use which names. A classic way to
solve a namespace issue is to divide the namespace up into domains. On the
Internet, host names are sectioned off into domains, so that I can have a host
named
Pluto
or
www
and so can lots of others—because each host is
qualified
by its domain (e.g.,
myco.com
). Thus
www.myco.com
isn't confused with
www.otherco.com
or
www.hisgroup.org
. Each host is named
www
, but each
is unique because of the qualifying domain.
Java solves the problem in much the same way, but with the names in the
reverse order. Think of the “host” as the class name; the “domain” name, used
to sort out identical host names, is, in Java parlance, the
package name
. When
you see a name like
com.myco.finapp.Account
, that can be a Java package
com.myco.finapp
qualifying a class named
Account
.
Beyond just keeping the namespace clean, Java packages serve another
important function. They let you group together similar classes and interfaces
to control access to them. Classes within the same package can access each
others' members and methods even when they are not declared
public
, provid-
ed they are not declared to be
private
. This level of intimacy, sometimes
called
package protection
, means that you should group classes together that are
related, but avoid grouping too many classes together. It's tempting just to
put all your classes for a project into the same package, for example,
com.myco.ourproject
, but you will provide better safety and perhaps pro-
mote better reuse by grouping them into several smaller packages, for example,
com.myco.util
,
com.myco.financial
, and
com.myco.gui
.
The
package
Statement
3.3.1
So how do you make a Java class part of a package? It's easy—you just put, as
the first (noncomment) line of the file, the
package
statement, naming the
package to which you want this class to belong. So if you want your
Account
class to be part of the
com.myco.financial
package, your Java code would
look as shown in Example 3.23.