[英]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. 但是,以上代码将引发NullPointerException。 And I know that's because invoking the method 'addSubClassess' actually happens before the creation of the subclass.
而且我知道这是因为调用方法'addSubClassess'实际上是在创建子类之前发生的。 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. 有一个名为Shape的基类,它具有许多子类,例如Circle,Square和Triangle。 Class Shape has a method name 'erase' to erase the shape, which is overrode by subClasses.
类的形状有一个名为“ erase”的方法来擦除形状,该方法被子类覆盖。 Class Shape has another private method name 'eraseAll' to erase all the shape created.
类Shape具有另一个专用方法名称“ eraseAll”,以擦除所有创建的形状。 So if I wanna invoke the 'eraseAll', I should know what exactly created and then remove them at one time.
因此,如果我想调用“ eraseAll”,我应该知道确切创建的内容,然后一次将其删除。
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. 如果要在基类中计算Sub的所有实例,则subClasses不能是实例变量。 That would create a new list for each instance of Sub.
这将为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. 通过静态初始化列表,Base构造函数将不需要创建子类ArrayList的新实例。
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. 如果您需要一个基本实例,则应删除
static
字。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.