The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Learning the Java Language
Lesson: 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.

in the Graphics.java file
abstract class Graphic {
    . . .
}

in the Circle.java file
public class Circle extends Graphic implements Draggable {
    . . .
}

in the Rectangle.java file
public class Rectangle extends Graphic implements Draggable {
    . . .
}

in the Draggable.java file
public 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 Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search