java - 继承类的 protected 静态成员

标签 java inheritance static polymorphism

我有一些类,它们都继承相同的基类,并且需要有一个在启动时在函数中初始化的静态属性。我是这样实现的:

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/

相关文章:

c++ - move 构造函数不是继承的,也不是默认生成的

html - 是否可以将 google adsense 添加到 Bitbucket 页面

c - 指针和函数外部分配或静态变量和内部分配?

java - 无法写入 Excel 文件,出现 OpenXML4JRuntimeException

Java REST - POST 到 REST 之后调用方法

c# - 继承问题 - 从 Access 数据库文件和 SQL Express 中检索数据

java - 静态变量失去其值

java - maven 依赖项升级后 Jenkin 构建失败

java.lang.ClassNotFoundException : org. apache.poi.xssf.usermodel.XSSFWorkbook

java - 实现 "static abstract and inheritable"方法的排序