鉴于这种情况:
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); } }
类Cat中的方法genericmethod()绝对不会覆盖超类方法(并且编译器会抱怨,如果我添加@Override签名)这是合理的,因为对类型T的要求是不同的.
但是我不太明白,编译器如何决定在main方法中调用cat.genericmethod(cat)中使用哪两种方法.因为实际上这两种方法都是可见的并且都适用.我本来期望编译器错误,如“ambigous函数调用”.有人可以解释这种行为吗?
解决方法
由于子类方法的泛型类型绑定,这两种方法具有不同的擦除.
对于超类方法,擦除是:
public void genericmethod(Object t)
对于子类方法,擦除是:
public void genericmethod(Cat t)
重载解析规则的方法选择具有最佳匹配参数的方法.因此,当您传递Cat参数时,将选择第二个(子类)方法.