Java Reference
In-Depth Information
An application can consist of any number of packages. If the widget application
contains a few classes that represent widget objects, they could be placed within the
org.juneau.widget
package. The application may have interfaces that can be
used to interact with the widget objects. In this case, a package named
org.juneau.interfaces
may also exist to contain any such interfaces.
How It Works
Java packages are useful for organizing source files, controlling access to different
classes, and ensuring that there are no naming conflicts. Packages are represented by a
series of physical directories on a file system, and they can contain any number of Java
source files. Each source file must contain a
package
statement before any other
statements in the file. This
package
statement lists the name of the package in which
the source file resides. In the solution to this recipe, the source included the following
package
statement:
package org.juneau;
This
package
statement indicates that the source file resides within a directory
named
juneau
, and that directory resides within another directory named
org
.
Package-naming conventions can vary by company or organization. However, it is im-
portant that words are in lowercase so they do not conflict with any Java class file
names. Many companies or organizations will use the reverse of their domain name for
package naming. However, if a domain name includes hyphens, underscores should be
used instead.
Note
When a class resides within a Java package, it is no longer referenced by only
the class name, but instead the package name is prepended to the class name, which is
known as the
fully qualified
name. For instance, because the class that resides within the
file
JuneauWidgets.java
is contained within the
org.juneau
package, the class
is referenced using
org.juneau.JuneauWidgets
, not simply
JuneauWidgets
.
An identically named class can reside within a different package (for instance,
org.java8recipes.JuneauWidgets
).
Packages are very useful for establishing levels of security as well as organization.
By default, different classes that reside within the same package have access to each