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:
-
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.
You can easily create your own packages and put any number of class
and interface definitions in them.
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.
This section shows you where to put your java
and .class files so that the JDK tools can
find your classes.
|