Importing a Package

Purpose:

To allow reference to a package or type declared in another package without a full package name.

Mechanics:

import <package name>;
import <package name>.<class name>;
import <package name>.<interface name>;
import <package name>.*;

Example:

import cs015.SP.*;

Usage:

  • <package name>is a valid package identifier which is not the current package.
  • <class name> is any public class defined in <package name>.
  • <interface name> is any public interface defined in <package name>.
  • If a package is imported, the public interfaces and classes in that package can be referenced with only the last part of the package name. For example, if cs015.SP is imported, then the public class CloudShape can be referenced with the name SP.CloudShape.
  • If a particular public class or interface is imported, then it can be referenced as if it wrere in the same package. For example, if cs015.SP.CloudShape is imported, then the public class CloudShape can be referenced with the name CloudShape.
  • If * is given as the class or interface name, then Java imports every public class and interface in that package. Therefore, any public class can be referenced using just the class name.

Restrictions:

  • import must be used with caution, since attempting to import a public class with the same name as a class defined in the current package causes compile-time errors. This can always be avoided by using scoping (always providing the full package and class name) for every class reference.
  • Java always imports java.lang.* for every file at compile-time.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu