Java Reference
In-Depth Information
public class Test {
public static void main(String[] args) {
m1(); // C1.m1() will be called
}
}
Static Import Rule #2
Using single-static-import declaration to import two static members with the same simple name is not allowed.
The following static import declarations generate an error because both of them import the static member with the
same simple name of
m1
:
import static p1.C1.m1;
import static p1.C2.m1; // An error
Static Import Rule #3
If a static member is imported using a single-static import declaration and there exists a static member in the
same class with the same name, the static member in the class is used. The following is the code for two classes,
p1.A
and
p2.Test
:
// A.java
package p1;
public class A {
public static void test() {
System.out.println("p1.A.test()");
}
}
// Test.java
package p2;
import static p1.A.test;
public class Test {
public static void main(String[] args) {
test(); // Will use p2.Test.test() method, not p1.A.test() method
}
public static void test() {
System.out.println("p2.Test.test()");
}
}
p2.Test.test()
The
Test
class imports the
static
method
test()
from class
p1.A
using a single-static import declaration. The
Test
class also defines a
static
method
test()
. When you use the simple name,
test
, to call the
test()
method in
the
main()
method, it refers to
p2.Test.test()
method, not the one imported by the
static
import.