Previous | Next | Trail Map | Learning the Java Language | More Features of the Java Language

Creating and Using Packages

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 in java.io, and the GUI widget classes are in java.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.

abstract class Graphic {
    . . .
}
class Circle extends Graphic implements Draggable {
    . . .
}
class Rectangle extends Graphic implements Draggable {
    . . .
}
interface Draggable {
    . . .
}
You should bundle these classes and the interface together in a package, for several reasons:

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 your java and .class files so that the JDK tools can find your classes.


Previous | Next | Trail Map | Learning the Java Language | More Features of the Java Language