To be more precise
- it is NOT that we are not allowed to import classes with same simple name as class importing it,
- but we are not allowed to name importing class same as any class which is already imported.
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:
package a;
class B{}
package b;
class B{
a.B objectPackageaB; //legal - full-package-name so no ambiguity
b.B objectPackagebB; //legal - full-package-name so no ambiguity
B objectB; //legal, as now it can only represent B from package "b" -> b.B
}
Now lets add import a.B
package b;
import a.B; // <---
class B {
b.B objectbB; //still legal, full-package-name so no ambiguity
a.B objectaB; //still legal, full-package-name so no ambiguity
B objectB; //ambiguous, so ILLEGAL. Which type B should represent? a.B OR b.B?
}
IF Java would not prevent such situation, it would need to make decision what type B objectB
should represent.
We have two options:
- it would represent
b.B
so type which is importing. But that means to use B
from a
package we still would need to write it as a.B
, which means import a.B;
is redundant/dead code which would only be confusing programmers.
- it would represent
a.B
so type which is imported. But that would feel unnatural since inside class B{ }
, B
would 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.