Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


Using the Classes and Interfaces from a Package

To import a specific class or interface into the current file (like the Circle class from the graphics package created in the previous section) use the import statement:
import graphics.Circle;
The import statement must be at the beginning of a file before any class or interface definitions. It makes the class or interface available for use by the classes and interfaces defined in that file.

If you want to import all the classes and interfaces from a package-- for instance, the entire graphics package--use the import statement with the asterisk (*) wildcard character:

import graphics.*;
If you try to use a class or interface from a package that has not been imported, the compiler will issue a fatal error:
testing.java:4: Class Circle not found in type declaration.
	Circle circle;
	^
Note that only the classes and interfaces that are declared to be public can be used by classes outside of the package that they are defined in.

The default package (a package with no name) is always imported for you. The runtime system automatically imports the java.lang package for you as well. If by some chance the name of a class in one package is the same as the name of a class in another package, you must disambigutate the names by prepending the package name to the beginning of the class. For example, previously we defined a class named Rectangle in the graphics package. The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported then the following line of code (and others that attempt to use the Rectangle class) is ambiguous:

Rectangle rect;
In such a situation you have to be more specific and indicate exactly which Rectangle class you want:
graphics.Rectangle rect;
You do this by prepending the package name to the beginning of the class name and separating the two with a period.


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces