Java package

This is an old revision of this page, as edited by 208.251.159.3 (talk) at 15:56, 27 January 2006 (Creation of JAR Files). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Java source files belonging to the same category or provide similar functionality can be packed into a Java package. Java packages are stored in compressed files called JAR files. Inside the package the files can be stored hierachically, therefore it is possible to combine several subdirectories into one package.

Using packages

To use a package inside a Java source file, it is convenient to import the classes from the package with an import statement. The statement

import java.awt.event.*;

imports all classes from the java.awt.event package, while

import java.awt.event.ActionEvent;

imports only the ActionEvent class from the package. After either of these import statements, the ActionEvent class can be referenced using its simple class name:

ActionEvent myEvent = new ActionEvent();

Classes can also be used directly without an import statement by using the fully-qualified name of the class. For example,

java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent();

doesn't require a preceding import statement.

Creation of JAR Files

In Java source files the package the file belongs to is specified with the package keyword.

package java.awt.event;

JAR Files are created with the jar command-line utility. The command

jar cf myPackage.jar *.class

compresses all *.class files into the JAR file myPackage.jar.

Packages in J2SE 1.5