Packages and Interfaces
his chapter examines two of Java's most innovative features: packages and interfaces.
Packages are containers for classes that are used to keep the class name space
compartmentalized. For example, a package allows you to create a class named List,
which you can store in your own package without concern that it will collide with some
other class named List stored elsewhere. Packages are stored in a hierarchical manner and
are explicitly imported into new class definitions.
In previous chapters, you have seen how methods define the interface to the data in
a class. Through the use of the interface keyword, Java allows you to fully abstract the
interface from its implementation. Using interface, you can specify a set of methods that
can be implemented by one or more classes. The interface, itself, does not actually define
any implementation. Although they are similar to abstract classes, interfaces have an
additional capability: A class can implement more than one interface. By contrast, a class
can only inherit a single superclass (abstract or otherwise).
In the preceding chapters, the name of each example class was taken from the same
name space. This means that a unique name had to be used for each class to avoid name
collisions. After a while, without some way to manage the name space, you could run out
of convenient, descriptive names for individual classes. You also need some way to be
assured that the name you choose for a class will be reasonably unique and not collide
with class names chosen by other programmers. (Imagine a small group of programmers
fighting over who gets to use the name "Foobar" as a class name. Or, imagine the entire
Internet community arguing over who first named a class "Espresso.") Thankfully, Java
provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package. The package is both a naming and a visibility
control mechanism. You can define classes inside a package that are not accessible by
code outside that package. You can also define class members that are only exposed
to other members of the same package. This allows your classes to have intimate
knowledge of each other, but not expose that knowledge to the rest of the world.
Search WWH :