Java Reference
In-Depth Information
The other form of import is the “on-demand type import.” In this form, you specify
the name of a package followed by the characters .* to indicate that any type from
that package may be used without its package name. Thus, if you want to use several
other classes from the package in addition to the File class, you can simply
import the entire package:
a x
import* ; // Use simple names for all classes in
This on-demand import syntax does not apply to subpackages. If I import the
java.util package, I must still refer to the class
by its fully qualified name.
Using an on-demand type import declaration is not the same as explicitly writing
out a single type import declaration for every type in the package. It is more like an
explicit single type import for every type in the package that you actually use in your
code. This is the reason it's called “on demand”; types are imported as you use them.
Naming conlicts and shadowing
import declarations are invaluable to Java programming. They do expose us to the
possibility of naming conflicts, however. Consider the packages java.util and
java.awt . Both contain types named List .
java.util.List is an important and commonly used interface. The java.awt pack‐
age contains a number of important types that are commonly used in client-side
applications, but java.awt.List has been superseded and is not one of these
important types. It is illegal to import both java.util.List and java.awt.List in
the same Java file. The following single type import declarations produce a compila‐
tion error:
import java.util.List ;
import java.awt.List ;
Using on-demand type imports for the two packages is legal:
import java.util.* ; // For collections and other utilities.
import java.awt.* ; // For fonts, colors, and graphics.
Difficulty arises, however, if you actually try to use the type List . This type can be
imported “on demand” from either package, and any attempt to use List as an
unqualified type name produces a compilation error. The workaround, in this case,
is to explicitly specify the package name you want.
Because java.util.List is much more commonly used than java.awt.List , it is
useful to combine the two on-demand type import declarations with a single-type
import declaration that serves to disambiguate what we mean when we say List :
import java.util.* ; // For collections and other utilities.
import java.awt.* ; // For fonts, colors, and graphics.
import java.util.List ; // To disambiguate from java.awt.List
Search WWH ::

Custom Search