Java Reference
In-Depth Information
In the first form, ClassName may be used as a shorthand for a fully qualified
class name. In the second, all classes in a package may be abbreviated with
the corresponding class name.
For example, with the import directives
import java.util.Date;
import java.io.*;
we may use
Date today = new Date( );
FileReader theFile = new FileReader( name );
Using the import directive saves typing. And since the most typing is
saved by using the second form, you will see that form used often. There are
two disadvantages to import directives. First, the shorthand makes it hard to
tell, by reading the code, which class is being used when there are a host of
import directives. Also, the second form may allow shorthands for unintended
classes and introduce naming conflicts that will need to be resolved by fully
qualified class names.
Suppose we use
Careless use of the
import directive can
introduce naming
conflicts.
import java.util.*; // Library package
import weiss.util.*; // User-defined package
with the intention of importing the java.util.Random class and a package that
we have written ourselves. Then, if we have our own Random class in
weiss.util , the import directive will generate a conflict with weiss.util.Random
and will need to be fully qualified. Furthermore, if we are using a class in one
of these packages, by reading the code we will not know whether it originated
from the library package or our own package. We would have avoided these
problems if we had used the form
import java.util.Random;
and for this reason, we use the first form only in the text and avoid “wildcard”
import directives.
The import directives must appear prior to the beginning of a class decla-
ration. We saw an example of this in Figure 2.19. Also, the entire package
java.lang is automatically imported. This is why we may use shorthands such
as Math.max , Integer.parseInt , System.out , and so on.
In versions of Java prior to Java 5, static members such as Math.max
and Integer.MAX_VALUE could not be shortened to simply max and MAX_VALUE .
java.lang.*
is automatically
imported.
 
Search WWH ::




Custom Search