Java Reference
In-Depth Information
Extend interfaces
Create default and static interface methods
T his chapter examines two of Java's most innovative features: packages and interfaces.
Packages are groups of related classes. Packages help organize your code and provide an-
other layer of encapsulation. An interface defines a set of methods that will be implemen-
ted by a class. Thus, an interface gives you a way to specify what a class will do, but not
how it will do it. Packages and interfaces give you greater control over the organization of
your program.
Packages
In programming, it is often helpful to group related pieces of a program together. In Java,
this is accomplished by using a package. A package serves two purposes. First, it provides
a mechanism by which related pieces of a program can be organized as a unit. Classes
defined within a package must be accessed through their package name. Thus, a package
provides a way to name a collection of classes. Second, a package participates in Java's
access control mechanism. Classes defined within a package can be made private to that
package and not accessible by code outside the package. Thus, the package provides a
means by which classes can be encapsulated. Let's examine each feature a bit more closely.
In general, when you name a class, you are allocating a name from the namespace . A
namespace defines a declarative region. In Java, no two classes can use the same name
from the same namespace. Thus, within a given namespace, each class name must be
unique. The examples shown in the preceding chapters have all used the default (global)
namespace. While this is fine for short sample programs, it becomes a problem as programs
grow and the default namespace becomes crowded. In large programs, finding unique
names for each class can be difficult. Furthermore, you must avoid name collisions with
code created by other programmers working on the same project, and with Java's library.
The solution to these problems is the package because it gives you a way to partition the
namespace. When a class is defined within a package, the name of that package is attached
to each class, thus avoiding name collisions with other classes that have the same name,
but are in other packages.
Since a package usually contains related classes, Java defines special access rights to
code within a package. In a package, you can define code that is accessible by other code
within the same package but not by code outside the package. This enables you to create
self-contained groups of related classes that keep their operation private.
Search WWH ::




Custom Search