gpt4 book ai didi

java - ArrayList和多态性

转载 作者:行者123 更新时间:2023-12-01 17:05:14 25 4
gpt4 key购买 nike

如果有人能在这里指出问题和可能的解释,那将会有很大的帮助。

class Parent{}    
public class ChildClass extends Parent{
/*Main class*/
public static void main(String[] args) {

ArrayList<ChildClass> a3 = new ArrayList<ChildClass>();
foo(a3);
}
/*another function*/
static void foo(ArrayList<Parent> obj) {
}

这会引发以下编译错误。

The method foo(ArrayList<Parent>) in the type ChildClass is not applicable for the arguments (ArrayList<ChildClass>)

多态性规则应该允许我这样做。正确的?毕竟 ChildClass 是一个 Parent。似乎有什么问题?

最佳答案

ChildClass是-a Parent ,但是ArrayList<ChildClass>不是ArrayList<Parent> 。如果您考虑这段代码,就应该清楚原因:

ArrayList<ChildClass> a3 = new ArrayList<>();
foo(a3);
ChildClass c = a3.get(0);

...

static void foo(ArrayList<Parent> obj) {
obj.add(new Parent());
}

如果上面的代码碰巧编译时没有错误,那么它将是类型不安全的,并且实际上在运行时失败,并显示 ClassCastException .

因此,为了使关系“ArrayList<ChildClass> is-a ArrayList<Parent>”真正有意义,这两个事实必须同时为真:

  1. ChildClass是-a Parent ;
  2. Parent是-a ChildClass .

一般来说,只有在 ChildClass 时才成立。与 Parent 类型相同,以不同的名称。因此,我们得出了 Java 应用的真正规则,称为“类型不变性”:它既不支持 ArrayList<ChildClass>是一个ArrayList<Parent> ,也不是ArrayList<Parent>是一个ArrayList<ChildClass> .

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

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