Java 中的集合可以容纳不同的 children 类 吗?

Can a Collection in Java hold different children classes?

我有三个 class。 Class A(摘要 class)是 class B 和 class C 的 parent。

我需要一个可以同时容纳 objects 个 BC 的容器。

我试过这样做

ArrayList<A> myCollection = new ArrayList<A>();

然后

myCollection.add(b); //b is an instance of class B

我收到这个错误:

The method add(A) in the type ArrayList is not applicable for the arguments (B)

有没有一种方法可以将 class BC 的 objects 存储在我的 ArrayList 中?或者我可以使用另一种数据结构吗?

试试下面的代码:

ArrayList<A> list = new ArrayList<>();
B b = new B();
C c = new C();

// Adding items
list.add(b);
list.add(c);

你可以试试:

 ArrayList<? extends A> myCollection = new ArrayList<>();

是的,看这个:

public class Fo {

  static class A{}
  static class B extends A{}

  static void f() {
    List<A> as = new ArrayList<A>();
    as.add(new B());
  }

}

是的,你可以列出超级class。

List<A> l = new ArrayList<A>();
        l.add(new B());
        l.add(new C());

100% 正确,你有一个超级列表 class,并且由于 BC是classA的对象,那么是有效的...

并考虑通过接口引用对象,您应该倾向于使用接口而不是 classes 来引用对象,

If you get into the habit of using interfaces as types, your program will be much more flexible. If you decide that you want to switch implementations, all you have to do is change the class name in the constructor (or use a different static factory).