If I have a class names ClassX in package a.b.c, and I want to import the class a.b.x.ClassX
Is there some restriction in Java preventing me from doing so? As far as usage goes, I can always use the fully qualified name of the imported class, right?
Eclipse seems to be unable to resolve this import, I need to know if there is a restriction in Java itself that is causing the problem.
Is the following code legal:
a\b\c\ClassX.java :
package a.b.c;
public class ClassX {
//
}
a\b\x\ClassX.java :
package a.b.x;
import a.b.c.ClassX;
public class ClassX {
public static void main(String[] args) {
a.b.c.ClassX newObj = new a.b.c.ClassX();
}
}
If no, then why?
To be more precise
Attempting to do so will result in error message:
[NameOfImportingClass] is already defined in this compilation unit.Purpose of this restriction is to prevent name ambiguity/clashes.
For example without imports all below is legal:
Now lets add
import a.BIF Java would not prevent such situation, it would need to make decision what type
B objectBshould represent.We have two options:
b.Bso type which is importing. But that means to useBfromapackage we still would need to write it asa.B, which meansimport a.B;is redundant/dead code which would only be confusing programmers.a.Bso type which is imported. But that would feel unnatural since insideclass B{ },Bwould represent some other type!.Neither of above solutions are good.
If there is no good solution to a problem, best option is to prevent from appearing.