鉴于这种情况:
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函数调用”.有人可以解释这种行为吗?
解决方法
原文地址:https://www.jb51.cc/java/121389.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。