More Features of the Java Language |
To make classes easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes into packages.
Definition: A package is a collection of related classes and interfaces that provides access protection and namespace management.
The classes and interfaces that are part of the JDK are members of various packages that bundle classes by function: applet classes are in
java.applet
, I/O classes are injava.io
, and the GUI widget classes are injava.awt
. You can put your classes and interfaces in packages, too.Let's look at a set of classes and examine why you might want to put them in a package. Suppose you write a group of classes that represent a collection of graphics objects such as circles, rectangles, lines, and points. You also write an interface
Draggable
that classes implement if they can be dragged with the mouse by the user.You should bundle these classes and the interface together in a package, for several reasons:abstract class Graphic { . . . } class Circle extends Graphic implements Draggable { . . . } class Rectangle extends Graphic implements Draggable { . . . } interface Draggable { . . . }
- You and other programmers can easily determine that these classes and interfaces are related.
- You and other programmers know where to find classes and interfaces that provide graphics-related functions.
- The names of your classes won't conflict with class names in other packages because the package creates a new namespace.
- You can allow classes within the package to have unrestricted access to each other, yet still restrict access for classes outside the package.
Creating a Package
You can easily create your own packages and put any number of class and interface definitions in them.Using Package Members
To use the classes and interfaces defined in one package from within another package, you need to import the package. The classes and interfaces that you import must be declared public.Managing Source and Class Files
This section shows you where to put yourjava
and.class
files so that the JDK tools can find your classes.
More Features of the Java Language |