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
publicclass defined in <package name>. - <interface name> is any
publicinterface defined in <package name>. - If a package is imported, the
publicinterfaces and classes in that package can be referenced with only the last part of the package name. For example, ifcs015.SPis imported, then thepublicclassCloudShapecan be referenced with the nameSP.CloudShape. - If a particular
publicclass or interface is imported, then it can be referenced as if it wrere in the same package. For example, ifcs015.SP.CloudShapeis imported, then thepublicclass CloudShape can be referenced with the nameCloudShape. - If * is given as the class or interface name, then Java imports
every
publicclass and interface in that package. Therefore, anypublicclass can be referenced using just the class name.
Restrictions:
importmust be used with caution, since attempting to import apublicclass 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.
email suggestions to: cs015tas@cs.brown.edu
