加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 泛型和继承?

发布时间:2020-12-15 04:27:36 所属栏目:Java 来源:网络整理
导读:参见英文答案 Java: Can’t to generic List? extends Parent mylist????????????????????????????????????4个 public static void main(String... args) { ListChild list1 = new ArrayListChild(); method2(list1);}public static void method2(ListParent
参见英文答案 > Java: Can’t to generic List<? extends Parent> mylist????????????????????????????????????4个

public static void main(String... args) {
    List<Child> list1 = new ArrayList<Child>();
    method2(list1);
}

public static void method2(List<Parent> list1) {
}

我得到以下编译错误

The method method2(List) is undefined …

上述问题可以通过修改List< Parent>来解决. list1到List<?扩展父>列表1.

但是如果我尝试添加下面的子对象

public static void method2(List<? extends Parent> list1) {
    Child child1 = new Child();
    list1.add(child1);
}

它再次出现编译错误

The method add(capture#1-of ? extends Parent) in the type List is not applicable for the arguments (Child)

所以我的问题是如果List< Child>可以作为参数传递给List<?扩展父> list1为什么我们不能在List<?下添加子对象扩展父>?

解决方法

这是一个非常普遍的误解. Child扩展Parent的事实不会使List< Child>扩展名单< Parent>.在像这样的情况下听起来非常不直观,但确实如此.来自java教程:

Given two concrete types A and B (for example,Number and Integer),
MyClass< A> has no relationship to MyClass< B>,regardless of whether or
not A and B are related. The common parent of MyClass and
MyClass is Object.

阅读this了解详情.

至于添加到列表,简短的答案是:想象一下你有另一个类Child2扩展Parent,现在,你在method2接收的列表(List<?extends Parent> list1)可以是List< Child1&gt ;或列表< Child2>.因此,鉴于第二种情况是可能的,添加Child1对象不是类型安全的.

现在,你不能添加的事实并不意味着你不能做其他有用的东西,比如获得大小等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读