|
|
Objects, Classes, and Interfaces |
To import a specific class or interface into the current file (like the Circle class 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 and 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 Date not found in type declaration. Date date; ^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 disambiutate the names by prepending the package name to the beginning of the class. For example, previously we defined a class named Rectangle in the
graphicspackage. Thejava.awtpackage also contains a Rectangle class. If bothgraphicsandjava.awthave been imported then the following line of code (and others that attempt to use the Rectangle class) is ambiguous:In such a situation you have to be more specific and indicate exactly which Rectangle class you want:Rectangle rect;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 |