Java Basics  «Prev  Next»

Lesson 5Defining and importing packages
ObjectiveDefine, import, and add classes to packages.

Defining and importing Packages in Java

Placing classes into a package

Packages are defined using the keyword package. If the package keyword appears at the top of a Java source file, all the classes defined within that file are placed within the named package.
The syntax is:

package packageName;

Using a class within a package

Code defined outside the package that needs classes declared within the package can access those classes in one of two ways.
One way is to precede each class name with the package name, as in:

classMyApplet 
extendsjava.applet.Applet { 
 // code body
} 

In the above code the Java Applet class is used.
It is defined inside the subpackage named applet, which is in the package named java. You can use the same kind of notation for your own packages by nesting them and specifying each nested package with a dot (.).
The other way is to import some or all of the classes you will need. Then you can simply refer to the classes by name. In that case, instead of the above definition for MyApplet, you could write:

import java.applet.Applet;
class MyApplet extends Applet { 
  // ----- Code goes here
} 

To import all the classes within a package, you can use a wildcard notation, as in:
import java.awt.*; 

which imports all classes in Java's AWT package.

Creating Packages

We will not create any packages in this course, but Sun's JDK 1.6 makes it easy to manage packages if you do decide to create your own later. After you have indicated that the classes in a particular file should be placed in a certain package, you can compile that file using the option -d, followed by the directory where you would like that package placed.
The javac compiler that comes with the JDK 1.6 will then create a new subdirectory named after the package and place your newly compiled classes into that subdirectory. This directory structure is Java's way of maintaining different classes in different packages.

Here are some additional tips on how directories and subdirectories are organized when you use the -d compiling option.
Take a short quiz by clicking on the link below
Package Two Quiz