I am doing a static import of members of class Long and Integer:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
Now if I am trying to use this variable MAX_VALUE and print it I will get an error:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
public class StaticImportDemo2 {
public static void main(String[] args) {
//Error :: The field MAX_VALUE is ambiguous
System.out.println("Print without static import Integer.MAX_VALUE "+MAX_VALUE);
}
}
This is fine. To remove the error i will have to remove one static import to resolve this ambiguity .
The main issue I am getting is, if I use wildcard *
with Integer class
static import, the class gets compiled with no errors:
import static java.lang.System.out;
import static java.lang.Integer.*;
import static java.lang.Long.MAX_VALUE;
public class StaticImportDemo2 {
public static void main(String[] args) {
System.out.println("Print without static import Integer.MAX_VALUE " + MAX_VALUE);
}
}
The ambiguity must still exist. Why does this compile with no issues?
Why does this compile with no issues?
Because the Java Language Specification says that it does. See chapter 6 and 7, but particularly from 6.4.1:
A type-import-on-demand declaration never causes any other declaration to be shadowed.
A static-import-on-demand declaration never causes any other declaration to be shadowed.
And that’s probably because it’s very convenient to be able to wildcard-import entire packages, but sometimes you’ll have to resolve conflicts. It would suck (particularly in pre-IDE days) if the only alternative was to explicitly import every item. So specific (non-wildcard) imports were given precedence. That way, you just specify which you mean for the ambiguous items you want to use.