我有一些类,它们都继承相同的基类,并且需要有一个在启动时在函数中初始化的静态属性。我是这样实现的:
public abstract class Base {
protected static Model model;
}
public class Inherited extends Base {
static {
model = initializationFunction();
}
}
public class OtherInherited extends Base {
static {
model = otherInitializationFunction();
}
}
// Example of use
Base[] inheriteds = new Base[] { new Inherited(), new OtherInherited() };
for (int i = 0; i < inheriteds.length; i++) {
doStuff(inheriteds[i]).model; // This will always use the same model (last defined)
}
因此类在开始时初始化静态成员。但它似乎为整个基类设置了 model 的值,因此所有类实际上都具有相同的 model。
我需要 model
是静态的,因为它每个子类只需要存在一次。我的问题是如何为每个子类拥有一个静态模型,同时仍然确保它在父类中定义(因此,如果一个类没有定义它,则它在父类中定义)。
继承类中 protected 静态成员的预期行为是什么?我应该如何让每个类的这个成员的版本仍然是静态的(我不希望它为每个实例重复)?
最佳答案
My problem is how to have one static model per subclass, while still ensuring it is defined in the parent class (so if a class doesn't define it, it is defined in the parent class).
不可能,因为,静态成员和多态性、继承不能并存
关于java - 继承类的 protected 静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21062787/