derry
derry

Reputation: 13

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). 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().

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? Is it possible to get a complete array without creating a new object?

Upvotes: 0

Views: 102

Answers (1)

David Lavender
David Lavender

Reputation: 8331

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.

Upvotes: 3

Related Questions