【问题标题】:ArrayList and Polymorphism [duplicate]ArrayList 和多态性
【发布时间】:2014-11-11 03:28:20
【问题描述】:

如果有人可以在这里指出问题和可能的解释,那将是非常有帮助的。

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 IS-A Parent。似乎是什么问题?

【问题讨论】:

  • 输入static void foo(ArrayList&lt;? extends Parent&gt; obj) {}
  • 谢谢,但我想解释一下为什么它没有编译。

标签: java oop polymorphism


【解决方案1】:

ChildClassParent,但ArrayList&lt;ChildClass&gt; 不是ArrayList&lt;Parent&gt;。如果你考虑这段代码,应该很清楚为什么:

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

...

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

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

因此,要使关系“ArrayList&lt;ChildClass&gt; is-a ArrayList&lt;Parent&gt;”真正有意义,这两个事实必须同时为真:

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

一般情况下,只有当ChildClassParent 类型相同,但名称不同时,这才是正确的。因此,我们得出了 Java 应用的真正规则,称为类型不变性:它既不认为 ArrayList&lt;ChildClass&gt;ArrayList&lt;Parent&gt;,也不认为 ArrayList&lt;Parent&gt;ArrayList&lt;ChildClass&gt;

【讨论】:

  • 所以总体而言,ArrayList 只会接受父项,而 ArrayList 也是如此。那是因为当我们弹出值时,它不知道正在提取哪个对象。正确的?附言上面的代码在我的 Eclipse 中也没有为我编译。不管怎样,我明白了。
  • 您可以将子级添加到ArrayList&lt;Parent&gt;,但您不能将ArrayList&lt;Child&gt; 传递给需要ArrayList&lt;Parent&gt; 的方法。至于编译,这是两个 sn-ps 代码,不能按原样编译。您必须将第一部分包含在方法中(例如 main)。
猜你喜欢
  • 2015-09-11
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2015-06-27
相关资源
最近更新 更多