简体   繁体   中英

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. It can only be Interface1 type. 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. What happens if a user wants to pass a different subtype of Interface1 into your method? The interface tells the user that they can, but your implementation of that interface disagrees. Hence the error.

Look up "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

public   SubTypeofInterface2 Method(SuperTypeofInterface1 a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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