Jan*_*nek 28 java import static-import
让我们说我们有这些包和类:
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() {
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道,为什么静态导入方法是合法的(不会导致编译时错误)在包中p3?我们将无法在test()方法中进一步使用它们,因为这样的使用将导致编译时错误.
为什么它与正常导入类不一样.让我们说我们想A1从包中导入类p1并p2进入p3:
package p3;
import p1.A1;
import p2.A1;
Run Code Online (Sandbox Code Playgroud)
这种导入是非法的,会导致编译时错误.
Joa*_*uer 42
方法静态导入的模糊性可以在方法调用时解决.
例如,如果您有两个方法的静态导入,如下所示:
void frobnicate(int i);
// and
void frobnicate(boolean b);
Run Code Online (Sandbox Code Playgroud)
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 two Foobar classes you want.
Also note that a single static import can import multiple names. According to the relevant section of the JLS (emphasis mine):
一个单静态进口报关进口的所有访问静态成员从类型指定简单的名称.
例如,如果frobnicate上面的两个方法位于同一个类中,则单个static导入可以同时导入它们.
| 归档时间: |
|
| 查看次数: |
4653 次 |
| 最近记录: |