Java Reference
In-Depth Information
The
import
declarations in your class definition go at the top of the file before any class
definitions (but after the package declaration, as you see in the next section).
Using individual
import
declarations or importing packages is mostly a question of your
own coding style. Importing a group of classes does not slow down your program or
make it any larger; only the classes that you actually use in your code are loaded as they
are needed. Importing specific classes makes it easier for readers of your code to figure
out where your classes are coming from.
NOTE
If you're familiar with C or C++, you might expect the
import
decla-
ration to work like
#include
and possibly result in a large exe-
cutable program because it includes source code from another
file. This isn't the case in Java:
import
indicates only where the
Java compiler can find a class. It doesn't do anything to expand
the size of a compiled class.
The
import
statement also. can be used to refer to constants in a class by name.
Normally, class constants must be prefaced with the name of the class as in
Color.black
,
Math.PI
, and
File.separator
.
An
import static
statement makes the constants in an identified class available in
shorter form. The keywords
import static
are followed by the name of an interface or
class and an asterisk. For example:
import static java.lang.Math.*;
This statement makes it possible to refer to the constants in the
Math
class,
E
and
PI
,
using only their names. Here's a short example of a class that takes advantage of this fea-
ture:
import static java.lang.Math.*;
public class ShortConstants {
public static void main(String[] arguments) {
System.out.println(“PI: “ + PI);
System.out.println(“” + (PI * 3));
}
}
Class Name Conflicts
After you have imported a class or a package of classes, you usually can refer to a class
name simply by its name without the package identifier. There's one situation where you