gpt4 book ai didi

java - 列表多态性

转载 作者:行者123 更新时间:2023-12-02 06:21:22 25 4
gpt4 key购买 nike

我有这些类(class):

class Parent {
public Parent() {
}
}

class ChildA extends Parent {
public ChildA() {
super();
}
}

class ChildB extends Parent {
public ChildB() {
super();
}
}

public ListClas(List(Parent) list) {
this.list=list;
}
}

我想运行 ListClas 构造函数,如下所示。

List<ChildA> list_childA = new ArrayList<ChildA>();

List<ChildB> list_childB = new ArrayList<ChildB>();

ListClas listClasA = new ListClas(list_childA);

ListClas listClasB = new ListClas(list_childB);

但是编译器会抛出错误。如何使用多态性正确地做到这一点?

最佳答案

如果您想要一个接受包含父类(super class)子类的列表的函数,您应该使用语法。

public ListClas(List<? extends Parent> list){
this.list=list;
}

它将接受两者。

ListClas listClasA = new ListClas(list_childA);

ListClas listClasB = new ListClas(list_childB);

关于java - 列表多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20981077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com