我有 A 类接口(interface),B、C 接口(interface)。 aA 扩展 A,aB 实现 B,cC 实现 C。但是如果我尝试使用 MultipleBounded Generics。它会显示使用 jdk 1.7 的编译错误。 请帮我改正错误。 LINK FOR REFERENCE
public class MultipleBounds {
public static void main(String args[])
{
D d1 = new D();
d1.print(new bB()); // compilation Error
d1.print(new cC()); // compilation Error
d1.print(new aA()); // It works no Issues
}
}
class A {
public void method() {
System.out.println("methodA");
}
}
interface B {
public void method();
}
interface C {
public void method();
}
class aA extends A {
public void method() {
System.out.println("methodaA");
}
}
class bB implements B {
public void method() {
System.out.println("methodbB");
}
}
class cC implements C {
public void method() {
System.out.println("methodcC");
}
}
class D<T extends A & B & C>
{
public void print(T t)
{
t.method();
}
}
最佳答案
由于您使用原始类型 D
来调用该方法,因此该类的所有通用信息都会丢失。并且方法 print
将被它的删除所取代。
现在,类型参数 T
的删除是其最左边的边界,即 A
。这在JLS §4.6中很明显。 :
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
所以,编译器看到的是这样的:
class D {
public void print(A t)
{
t.method();
}
}
这就是为什么它适用于 A
而不适用于 B
和 C
。类(class):Avoid using raw types.
关于java - Java 中的多个有界泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21203803/