gpt4 book ai didi

java 泛型多态性

转载 作者:行者123 更新时间:2023-12-02 09:40:20 25 4
gpt4 key购买 nike

在下面的代码中

public class Animal {

public void eat() {
System.out.println("Animal eating");
}
}

public class Cat extends Animal {

public void eat() {
System.out.println("Cat eating");
}

}

public class Dog extends Animal {

public void eat() {
System.out.println("Dog eating");
}
}

public class AnimalFeeder {
public void feed(List<Animal> animals) {
animals.add(new Cat());
animals.forEach(animal -> {
animal.eat();
});
}

public static void main(String args[]){
List<Animal> a = new ArrayList<Animal>();
a.add(new Cat());
a.add(new Dog());

new AnimalFeeder().feed(a);
/* List<Dog> dogs = new ArrayList<>();
dogs.add(new Dog());
dogs.add(new Dog());
new AnimalFeeder().feed(dogs); // not allowed
*/


}
}

我了解该提要 (List<Animal> animals)方法无法传递 List<Dog>, List<Cat>等等如果List<Dog>被允许,然后animals.add(new Cat());也可以添加,这是不可取的,因为运行时会删除类型。所以只有List<Animal>是允许的。

但是,我可以执行以下操作

List<Animal> a = new ArrayList<Animal>();
a.add(new Cat());
a.add(new Dog());
and still call new AnimalFeeder().feed(a);

当我运行该程序时,它给了我

Cat eating
Dog eating
Cat eating

我对多态通用概念的理解是“我们想要我们的List<Animal>”仅接受List<Animal>并且该列表仅包含动物,而不包含猫或狗,换句话说,仅包含动物”。不希望包含任何其他包含狗或猫的内容吗?对吗?如果是,为什么我可以通过 List<Animal> 包含狗,猫等。这与传递(假设允许)List<Dog>然后将new Cat()添加到狗列表不是一回事吗?

我希望我的问题很清楚。

我确实经历过 Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

但我能找到问题的答案吗?

谢谢

最佳答案

My understanding of polymorphic generic concept is that "we want our List to accept only List

正确

and also that that List contain only Animals, not Cat or Dog

不正确

一个List<Animal>可以包含 Animal 的实例类以及扩展 Animal 的任何类的实例。一个Dog和一个 Cat都是Animal s,因此可以将它们添加到 List<Animal> .

另一方面,当您使用类型 List<Dog> 时,你告诉编译器你的 List应该只包含 Dog实例(或 Dog 的子类实例),所以这样一个 List不能包含Cat s。

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

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