Generic method not overriding similar generic method in superclass -> Which one is used?

DanielBK :

Given this situation:

 public class Animal {

    public <T> void genericMethod(T t){
        System.out.println("Inside generic method on animal with parameter " + t.toString());
    }
}

public class Cat extends Animal {

    public <T extends Cat> void genericMethod(T t){
        System.out.println("Inside generic method on cat with parameter " + t.toString());
    }
}

public class Main {

    public static void main(String[] args) {
        Animal animal = new Animal();
        Cat cat = new Cat();
        cat.genericMethod(cat);
    }
}

The method genericMethod() in class Cat is definitely NOT overriding the superclass method (and the compiler complains if I add @Override signature) which is reasonable, as the requirements to the type T are different.

But I do not quite understand, how the compiler decides which of the two methods to use in the call cat.genericMethod(cat) in the main method. Because actually both methods are visible and both are applicable. I would have expected a compiler error like "ambigous function call" here. Can someone explain this behavior?

Eran :

These two methods have a different erasure due to the generic type bound of the sub-class method.

For the super class method the erasure is:

public void genericMethod(Object t)

For the sub class method the erasure is:

public void genericMethod(Cat t)

Method overloading resolution rules choose the method with the best matching arguments. Therefore when you pass a Cat argument, the second (sub-class) method is chosen.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465101&siteId=1