Java Reference
In-Depth Information
Let's go back to the problem of importing the p2.A class in a compilation unit, which already declares a class A .
The following code produces a compile-time error:
// B.java - Includes a new import declaration
package p1;
import p2.A;
class B {
A var1; // We want to use p2.A when you use A
}
class A {
// Code goes here
}
You have used only one single-type import declaration, not two, in the above code. Why did you get an error?
When you declare more than one class in the same compilation unit, most likely they are closely related and they
would refer to each other. You need to think as if Java imports each of the classes declared in the same compilation
unit using a single-type import declaration. You can think of the above code being transformed by Java as shown:
// B.java - Includes a new import declaration
package p1;
import p1.A; // Think of it being added by Java
import p1.B; // Think of it being added by Java
import p2.A;
class B {
A var; // We want to use p2.A when you use A
}
class A {
// Code goes here
}
Can you now see the problem? The class A has been imported twice, once by Java and once by you, and this is
the reason for the error. How do you refer to p2.A in your code anyway? It is simple. Use the fully qualified name p2.A
whenever you want to use p2.A in your compilation unit.
// B.java - Uses fully qualified name p2.A in class B
package p1;
class B {
p2.A var; // Use fully qualified name of A
}
class A {
// Code goes here
}
 
Search WWH ::




Custom Search