franksunnn
franksunnn

Reputation: 147

How to let the base class know what objects of sub classes created?

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!

Upvotes: 1

Views: 109

Answers (2)

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

Will this sample work for you? This anonymous block will be called for any of the subclassing constructors and the counters will be put into the map.

If you need this for a single base instance, word static should be removed.


public class Base{
  private static final Map<Class, Integer> counters = new HashMap();

  {
     synchronized(counters){
        Integer v = counters.get(getClass());
        v = v == null ? 0 : v;
        counters.put(getClass(), v + 1);  
     }
  }
}

Upvotes: 1

GregA100k
GregA100k

Reputation: 1395

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.

Upvotes: 1

Related Questions