Override generic method

According to the JLS (Java Language Specification):

The concept of a signature is intended to express the relationship between two methods whose signatures are not identical, but in which one can override the other. In particular, it allows a method whose signature does not use generic types to override any generic version of that method.

This code is based on the JLS example:

interface CollectionConverter<U> {
    <T> List<T> toList(Collection<T> c);

    void fooMethod(Class<?> c);

    <E>Comparable<E> method3(E e);

    Comparable<U> method4(U u);
}

class Overrider implements CollectionConverter<Integer> {
    @Override
    public List toList(Collection c) {
        return null;
    }

    @Override
    public void fooMethod(Class c) {

    }

    @Override
    public  Comparable method3(Object o) {
        return null;
    }

    @Override
    // compile error, have to change Object to Integer 
    public Comparable method4(Object u) {                       

        return null;
    }
}

      

According to the JLS, I understand why the first three methods work well, but I cannot understand why it method4

has a compilation error like this:

Method4 (Object) of type Overrider must override or implement supertype method.

+4


source to share


4 answers


Signature method4

in CollectionConverter

there

Comparable<U> method4(U u);

      

You declare Overrider

to implement CollectionConverter<Integer>

, thereby binding the type parameter U

to Integer

. Then the signature will be as follows:



Comparable<Integer> method4(Integer u);

      

You can declare method4(Object u)

in Overrider

, but this method signature does not override method4(Integer u)

that specified in the interface any more than if you weren't using generics at all.

+4


source


The problem is that the type variable is U

bound to Integer

at this point. If you change your ad to

public Comparable method4(Integer u) ...

      



this is an override

+2


source


Because in interface method4 is declared with the same type parameter as interface (U). If you change it to something else, it should work.

for example

<A> Comparable<A> method4(A a);

      

+1


source


In the specific case that you need to override a method with a generic parameter that does not have a generic return type, you need to ensure that the parameter's type is actually a child of that generic type.

For example:

protected Response updateResource(long id, T payload, RequestContext context){}

      

overlaps

@Override
protected Response updateResource(long id, Payload payload, RequestContext context){}

      

Thumbs up for IntelliJ IDEA Code> New ...> Override Methods ...

0


source







All Articles