[英]Override java generic method in interface
public <A extends Interface1,I extends Interface2> I Method(A a);
这是界面中的方法。 当我重写此接口的方法,我可以代替I
用它实现接口2但参数类的任何A
,如果它是接口1的子类被拒绝。 它只能是Interface1类型。 所以当我尝试:
public SubTypeofInterface2 Method(Interface1 a); //fine
public SubTypeofInterface2 Method(SubTypeofInterface1 a); // not accepted
为什么会这样?
仅当两个方法的擦除相同或实现类中的方法擦除与接口中的方法擦除兼容时,才认为实现类中的方法重写接口方法。
那么接口中方法的擦除是什么? 就像这样:
public Interface2 method(Interface1 a);
因此,从您的两种方法中:
public SubTypeofInterface2 Method(Interface1 a); //fine
public SubTypeofInterface2 Method(SubTypeofInterface1 a); // not accepted
仅第一个与擦除方法具有重写兼容性。 返回类型中的协变类型是允许的。
但是第二种方法不兼容。 覆盖时,参数中不允许使用协变类型。 这就是为什么它无法编译。
它的工作方式与普通的非泛型方法重写相同:
interface Test {
Object get(Object obj);
}
class TestImpl implements Test {
// Valid override
@Override
public String get(Object obj) { return null; }
// This doesn't override interface method.
public String get(String obj) { return null; }
}
这是因为您的方法需要能够处理Interface1的任何子类型。 如果用户想将Interface1的其他子类型传递到您的方法中,该怎么办? 该界面告诉用户他们可以,但是您对该界面的实现持不同意见。 因此,错误。
查找“ contravariance”。 方法参数处于相反位置。 即使Java很酷,可以支持这种子类型关系,您的子类也必须看起来像
public SubTypeofInterface2 Method(SuperTypeofInterface1 a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.