简体   繁体   English

在接口中重写Java通用方法

[英]Override java generic method in interface

public   <A extends Interface1,I extends Interface2> I  Method(A a);

This is a method in an interface. 这是界面中的方法。 When I get to override this interface method, I can replace I with any class which implements Interface2 but the parameter A is rejected if it is a subclass of Interface1. 当我重写此接口的方法,我可以代替I用它实现接口2但参数类的任何A ,如果它是接口1的子类被拒绝。 It can only be Interface1 type. 它只能是Interface1类型。 So when I try: 所以当我尝试:

 public   SubTypeofInterface2  Method(Interface1 a); //fine
 public   SubTypeofInterface2  Method(SubTypeofInterface1 a); // not accepted

Why does this happen? 为什么会这样?

The method in the implementing class is considered to override the interface method, only when erasures of both methods are identical or erasure of method in implementing class is override compatible with the erasure of method in interface. 仅当两个方法的擦除相同或实现类中的方法擦除与接口中的方法擦除兼容时,才认为实现类中的方法重写接口方法。

So what's the erasure of method in interface? 那么接口中方法的擦除是什么? It's like this: 就像这样:

public Interface2 method(Interface1 a);

So, out of your two methods: 因此,从您的两种方法中:

public   SubTypeofInterface2  Method(Interface1 a); //fine
public   SubTypeofInterface2  Method(SubTypeofInterface1 a); // not accepted

Only the first one is override compatible with the erased method. 仅第一个与擦除方法具有重写兼容性。 Covariant type in return type is allowed. 返回类型中的协变类型是允许的。

But the second method is not override compatible. 但是第二种方法不兼容。 Covariant type are not allowed in parameters while overriding. 覆盖时,参数中不允许使用协变类型。 That is why it fails to compile. 这就是为什么它无法编译。

It works the same way as the normal non-generic method overriding: 它的工作方式与普通的非泛型方法重写相同:

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; }
}

It's because your method needs to be able to handle any subtype of Interface1. 这是因为您的方法需要能够处理Interface1的任何子类型。 What happens if a user wants to pass a different subtype of Interface1 into your method? 如果用户想将Interface1的其他子类型传递到您的方法中,该怎么办? The interface tells the user that they can, but your implementation of that interface disagrees. 该界面告诉用户他们可以,但是您对该界面的实现持不同意见。 Hence the error. 因此,错误。

Look up "contravariance". 查找“ contravariance”。 Method arguments are in contravariant position. 方法参数处于相反位置。 Even if Java was cool enough to support this kind of subtyping relationship, your subclass would have to look like 即使Java很酷,可以支持这种子类型关系,您的子类也必须看起来像

public   SubTypeofInterface2 Method(SuperTypeofInterface1 a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM