|
|
Objects, Classes, and Interfaces |
To import a specific class or interface into the current file (like theCircleclass from thegraphicspackage created in the previous section) use theimportstatement:Theimport graphics.Circle;importstatement 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
graphicspackage--use theimportstatement 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; ^publiccan 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.langpackage 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 namedRectanglein thegraphicspackage. Thejava.awtpackage also contains aRectangleclass. If bothgraphicsandjava.awthave been imported then the following line of code (and others that attempt to use theRectangleclass) is ambiguous:In such a situation you have to be more specific and indicate exactly whichRectangle rect;Rectangleclass 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 |