Lets say we have these packages and classes:
package p1;
public class A1 {
public static void a() {}
}
package p2;
public class A1 {
public static void a() {}
}
package p3;
import static p1.A1.a;
import static p2.A1.a;
public class A1 {
public static void test() {
}
}
I am wondering, why the static import of methods is legal (won't result in compile time error) in package p3
? We won't be able to use them further in the test()
method as such usage will result in the compile time error.
Why it is not the same as with a normal import of classes. Lets say we would like to import classes A1
from packages p1
and p2
into p3
:
package p3;
import p1.A1;
import p2.A1;
such import is illegal and will result in the compile time error.
The ambiguity of the static imports of methods could be resolved at the point of the method invocation.
For example if you had a static import for two methods that look like this:
Then you could import and use both, because the compiler could tell which one to use, based on the arguments you pass in (
frobnicate(1)
calls the first one,frobnicate(true)
calls the second one).With classes, that's not possible:
Foobar a;
alone is not sufficient to tell you which of the twoFoobar
classes you want.Also note that a single static import can import multiple names. According to the relevant section of the JLS (emphasis mine):
For example if the two
frobnicate
methods above where located in the same class, a singlestatic
import could import them both.