0

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?

2
  • this refers to the current instance. Commented Jan 12, 2018 at 16:40
  • also, make the "child" array static Commented Jan 12, 2018 at 16:41

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Do I have to use a list? I rather do it with an array as i did not read about lists yet.
@derry Lists automatically grow, arrays are fixed size. So unless you want to implement logic to constantly create new arrays when the number of instances gets to big for your array you should go with a List. (As an ArrayList already has that work done for you)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.