Objects, Classes, and Interfaces |
To import a specific class or interface into the current file (like theCircle
class from thegraphics
package created in the previous section) use theimport
statement:Theimport graphics.Circle;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 theimport
statement with the asterisk (*
) wildcard character:If you try to use a class or interface from a package that has not been imported, the compiler will issue a fatal error:import graphics.*;Note that only the classes and interfaces that are declared to betesting.java:4: Class Circle not found in type declaration. Circle circle; ^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 namedRectangle
in thegraphics
package. Thejava.awt
package also contains aRectangle
class. If bothgraphics
andjava.awt
have been imported then the following line of code (and others that attempt to use theRectangle
class) is ambiguous:In such a situation you have to be more specific and indicate exactly whichRectangle rect;Rectangle
class you want:You do this by prepending the package name to the beginning of the class name and separating the two with a period.graphics.Rectangle rect;
Objects, Classes, and Interfaces |