How do I let the base class know which objects of subclasses are created?

advertisements

I wanna create a base class and some subclasses. And I wanna let the base class know what objects of sub classes created. I tried to invoke the method of base class from the constructor of the subclasses, just as follows:

class Base{
    private ArrayList<Base> subClasses;
    void addSubClassess(Base b){
        subClasses.add(b);
    }
    void calculateSubClasses(){
        System.out.println(subClasses.size());
    }
}

class Sub extends Base{
    Sub(){
        super.addSubClassess(this);
    }

}

public class Test{
    public static void main(String[] args){
        Sub s = new Sub();
        Base b = new Base();
        b.calculateSubClasses();
}

However, the above code will throw NullPointerException. And I know that's because invoking the method 'addSubClassess' actually happens before the creation of the subclass. So the method doesn't work expectedly.

So is there any way to deal with my problem? Here is an example to explain what I exactly want?

There is a base class named Shape, which has many subClasses, such as Circle, Square, Triangle. Class Shape has a method name 'erase' to erase the shape, which is overrode by subClasses. Class Shape has another private method name 'eraseAll' to erase all the shape created. So if I wanna invoke the 'eraseAll', I should know what exactly created and then remove them at one time.

I hope someone can help me. Thanks a lot!


If you are trying to have all instances of Sub get counted in on the base class, subClasses cannot be an instance variable. That would create a new list for each instance of Sub.

subClasses needs to be a static variable so that all instances share the same list.

private static java.util.ArrayList<Base> subClasses = new java.util.ArrayList<Base>();

By statically initializing the list, the Base constructor will not need to create a new instance of the subClasses ArrayList.