Java Reference
In-Depth Information
Let's discuss some of the rules about using import-on-demand declarations. The compiler uses the import-on-
demand declarations in resolving a simple name of a type after it has used all other means to resolve the simple name.
It is valid to import a class with the same simple name using a single-type import declaration as well as an import-on-
demand declaration. In such a case, the single-type import declaration is used. Suppose you have three Classes and
objects: p1.A , p2.A , and p2.B . Suppose you have a compilation unit as follows:
// C.java
package p3;
import p1.A;
import p2.*;
class C {
A var; // Will always use p1.A (not p2.A)
}
In the above code, class A has been imported twice: once using simple type import declaration from package p1 ,
and once using import-on-demand declaration from package p2 . The simple name A is resolved to p1.A because a
single-type import declaration always takes precedence over an import-on-demand declaration. Once the compiler
finds a class using a single-type import declaration, it stops the search there without looking for that class using any
import-on-demand declarations.
Let's change the import declarations in the above code to use import-on-demand declarations, as follows:
// C.java
package p3;
import p1.*;
import p2.*;
class C {
A var; // An error. Which A to use p1.A or p2.A?
}
Compilation of class C generates an error.
"C.java": reference to A is ambiguous, both class p2.A in p2 and class p1.A in p1 match at line 8,
column 5
The error message is loud and clear. When the compiler finds a class using an import-on-demand declaration,
it continues searching for the class in all import-on-demand declarations. If it finds the class with the same simple
name using multiple import-on-demand declarations, it generates an error. You can resolve the above compiler error
in several ways:
Use two single-type-import declarations.
Use one single-type import and one import-on-demand declaration.
Use fully qualified names for both classes.
 
Search WWH ::




Custom Search