我试图将由 super() 构造的 A 的所有子类存储在数组 child 中(在本例中为 B)。所有的 child 都在同一个包裹里。这是我的方法,但我不知道该类如何将自身存储在数组中或将自身作为参数传递给 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);
}
}
这可能吗?按照我的方法,只有在创建新的 B() 时才会添加 B 吗?是否可以在不创建新对象的情况下获得完整的数组?
最佳答案
public class A {
private static final List<A> instances = new ArrayList<>();
public A() {
instances.add(this);
}
public static List<A> getInstances() {
return instances;
}
}
现在 A.getInstances()
可以随时调用,并且将包含扩展 A 的任何内容的实例。
关于java - 创建类的子类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48230440/