简体   繁体   English

创建一个类的子类数组

[英]Creating an array of subclasses of a class

I'm trying to store all subclasses of A which are constructed by super() in the array child (in this case B). 我试图将由super()构造的A的所有子类存储在数组子级(在本例中为B)中。 All the children are in the same package. 所有的孩子都在同一个包中。 This is my approach but I don't know how the class could store itself inside an array or pass itself as argument to super(). 这是我的方法,但我不知道该类如何将自身存储在数组中或将自身作为参数传递给super()。

class A {
  static int i = 0;
  A[] child = new A[10]
  int someval;
  A(int val){
    someval = val;
    child[i] = ???;
    i++;
  }
}
class B extends A{
   B(){
     super(val);
   }
}

Is this even Possible? 这可能吗? With my approach B will only be added when a new B() is created? 用我的方法,只有在创建新的B()时才添加B吗? Is it possible to get a complete array without creating a new object? 是否可以在不创建新对象的情况下获得完整的数组?

public class A {
    private static final List<A> instances = new ArrayList<>();

    public A() {
        instances.add(this);
    }

    public static List<A> getInstances() {
        return instances;
    }
}

Now A.getInstances() can be called whenever you like, and will contain instances of anything that extends A. 现在,您可以随时调用A.getInstances() ,它将包含扩展A的任何实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM