Java – does not override generic methods in superclasses – > which one to use?
In view of 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 cat class will never override superclass methods (and the compiler will complain if I add @ override signature). This is reasonable because the requirements for type T are different
But I don't quite understand how the compiler decides to invoke cat. in the main method. Which two methods are used in generic method (CAT) Because in fact, both methods are visible and applicable I expected compiler errors, such as "ambigous function call" Can anyone explain this behavior?
Solution
Due to the generic type binding of subclass methods, the two methods have different erasures
For superclass methods, erasure is:
public void genericMethod(Object t)
For subclass methods, erasure is:
public void genericMethod(Cat t)
The method of overloading parsing rules selects the method with the best matching parameters Therefore, when you pass cat parameters, the second (subclass) method is selected