简体   繁体   English

如何让基类知道子类创建了哪些对象?

[英]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.

相关问题 据说当我们创建子类的对象时,会自动创建其超类的对象。 是真的吗 - It is said that when we create an object of a sub-class automatically the objects of its super-classes get created. is it true? “class 加载器创建的对象的方法和构造函数可能引用其他类”是什么意思? - what does “The methods and constructors of objects created by a class loader may reference other classes” mean? 如何让 VS Code 知道 Non-JDK Classes 的路径? - How to let VS Code know the path to Non-JDK Classes? 所有 Android 类的实际基类是什么? - What is the actual base class of all Android classes? 有没有办法获取(知道)从同一类中的一个类创建的所有对象? - Is there a way to get (know) all objects created from a class in the same class? 如何编写面向 Object 的程序来实例化具有超级 class、子类和接口的对象和接口 - How to write an Object Oriented Program to instantiate objects and interfaces with super class, sub-classes and interfaces 有没有办法知道哪个子类正在调用超类? - Is there a way to know what sub class is calling the super class? 对作为抽象类的子类实例的对象的ArrayList进行排序 - Sort ArrayList of objects that are instance of sub classes of abstract class 我是新手使用对象和类。 如何从用户创建的类中打印? - I'm new to using objects and classes. How do I print from within a user created class? 获取模块 java.base 中所有类的 Class 对象 - Get the Class objects for all classes in the module java.base
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM