Home Creating an array of subclasses of a class
Reply: 1

Creating an array of subclasses of a class

derry Published in 2018-01-12 16:37:46Z

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] = ???;
class B extends A{

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?

Mr Spoon
Mr Spoon Reply to 2018-01-12 16:43:05Z
public class A {
    private static final List<A> instances = new ArrayList<>();

    public A() {

    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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308776 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO