微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 不覆盖超类中类似泛型方法的通用方法 – >使用哪一个?

鉴于这种情况:
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参数时,将选择第二个(子类)方法.

原文地址:https://www.jb51.cc/java/121389.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐