Java 5: explicit import ignored in favor of nested type in super-class?
The following code compiles correctly in 1.4, but fails in 1.5.
Even though Main.java has an explicit import of "other.State", a plain reference toState is being resolved to thejava.lang.Thread.State enumeration (new in 1.5) instead of the explicitly imported class, and the marked statement below gives a compilation error ("enum types may not be instantiated").
What gives? How do I resolve this? (My class has to be called State for API reasons).
::::::::::::::
other/State.java
::::::::::::::
package other;
publicclass State{
public State(){}
}
::::::::::::::
test/Main.java
::::::::::::::
package test;
import other.State;// NOTE: explicit import!
publicclass Mainextends Thread{
publicvoid run(){
State s =new State();// ERROR: Thinks this is Thread.State?!
}
publicstaticvoid main(String[] args){
new Main().run();
}
}
> Use the fully-qualified name - "package.class"
Oh, of course that's the workaround, but why is the compiler ignoring an explicit import, and using the nested type in the superclass?
If the import is supposed to have no effect (i.e. nested types in superclasses are now supposed to overshadow explicitly imported classes), shouldn't the compiler warn or give an error about *that*?
And finally, isn't this a bit of undocumented namespace pollution?
> > Use the fully-qualified name - "package.class"
> Oh, of course that's the workaround
My bad. I've been reading the standard more carefully, and this would be a problem in 1.4 as well. It's just that 1.5 has added a public nested enum type called State to java.lang.Thread, which causes any imports of user-defined types called "State" to be shadowed.
Stupid namespace pollution.
References: sec 7.5.2 (Type-Import-On-Demand Declaration) and 6.3.1 (Shadowing Declarations).
In particular, imports shadow top-level types in other compilation units, and other explicitly imported types, but never anything else (including nested types, whether in this class or in a superclasses).
Case closed.