Java Reference
In-Depth Information
It is a compile-time error to import a type using a single-type-import declaration into a compilation unit, if a type
with the same simple name exists in the same compilation unit.
Tip
Let's resolve the compiler error with the code that needs to use classes from different packages with the same
simple name. The code is as follows:
// Test.java
package pkg;
import p1.A;
import p2.A; // A compile-time error
class Test {
A var1; // Which A to use p1.A or p2.A?
A var2; // Which A to use p1.A or p2.A?
}
You can resolve the error using one of the two following methods:
A .
Remove both import declarations and always use the fully qualified name of class
// Test.java
package pkg;
class Test {
p1.A var1; // Use p1.A
p2.A var2; // Use p2.A
}
A from one package, say p1 , and use the fully
Use only one import declaration to import class
qualified name of class A from other package p2 .
// Test.java
package pkg;
import p1.A;
class Test {
A var1; // Refers to p1.A
p2.A var2; // Uses the fully qualified name p2.A
}
If you want to use multiple classes in a compilation unit with the same simple name, but from different
packages, you can import a maximum of one class. For the rest of the classes, you must use the fully qualified name.
You have the option of using the fully qualified name for all classes.
Tip
 
Search WWH ::




Custom Search