Notes on Making Packages

 

Packages allow you to group your classes and interfaces.  A package is a “library” of related software.

 

There are zillions of classes defined for use with Java.  Packages can be used to avoid duplication of names. Duplicated names can be avoided by extending the name with a package name.  The class mystuff.Widget is distinct from yourstuff.Widget

 

Steps in creating a reusable class in a package:

  1. Define the public class.  If the class is not public, only other classes in the same package can use it.
  2. Choose a package name and add a package statement to the beginning of the source file (before import and class statements).
  3. Compile the class so it is placed in the appropriate package directory structure.
  4. In a new program, import the package and use the class.

 

The package name defines a directory structure for the location of the class files.  Changing the periods in a package name to slashes will produce the directory where the class files should be located.  These directories can be located in a jar file.

The –d option of javac can be used to set the destination directory for class files. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d c:\myclasses and the class is called com.mypackage.MyClass, then the class file is called c:\myclasses\com\mypackage\MyClass.class.

If -d is not specified, javac puts the class file in the same directory as the source file.

Note that the directory specified by -d is not automatically added to your user class path.

The convention for naming packages is to prefix the name with your Internet domain name in reverse order.  If you made an acme package at A&T, it might be called edu.ncat.acme.

 

Notes on import

The import statement tells the javac compiler to look in a specific package for the definitions of classes used in the program.  The javac compiler will search for the specified packages in the directories and jar files listed in the CLASSPATH.  You can import specific classes or large packages with a single import statement.  Putting a “.*” on the end of the package name indicates that all packages that start with the specified prefix will be imported.

Unlike C or C++ where the use of the #include is necessary to properly use library functions, the import statement in java is not required.  If you specify the full class names in your program, such as java.io.DataInputStream, you do not have to import the package.  The import statement allows you to use only the class name, such as DataInputStream.  The javac compiler will search the imported packages for the definition of the class and its methods.

The java.lang package is always implicitly imported, so you need not include it on an import statement.