根据我的理解,以下代码应该可以正常运行而不会出现任何编译错误。
但是,当我运行这个程序时,出现以下编译错误。
The member type B.D cannot be qualified with a parameterized type, since it is static. Remove arguments from qualifying type B
class B<X> {
interface C {
}
interface D<Y> {
}
}
class Test {
// compilation fails here
B<String>.D<String>[] arr = new B<String>.D<String>[10];
}
请帮助我理解这种行为。
最佳答案
以类似于内部 static
的方式类,嵌套接口(interface)与其外部类的实例没有关联,只有类本身。全部static
成员在 B
的所有实例之间共享, 无论 B
的类型参数。考虑:
class B<T> {
public static int shared = 0;
}
变量 shared
在B<String>
中是一样的, B<Integer>
, B<Object>
等等。试图在参数化 B
上访问它导致编译错误:
int copy = B<String>.shared; // <<== Does not compile
因此,B
的类型参数对arr
的声明没有影响,因此 Java 希望您将其删除:
B.D<String>[] arr = new B.D[10];
关于java - 具有通用接口(interface)的通用类编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45585845/