微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 抽象类或接口中的public static final字段

我有很多抽象类的子类,每个子类声明一个具有相同名称的公共静态final字段.我想在抽象超类中使用这个字段而不初始化它,并希望每个子类都被强制初始化它.

我正在考虑这个问题,因为抽象类的所有子类都声明了一个名为UNIQUE_ID的公共静态最终字符串字段,并且每个子类都必须声明具有该名称的字段.

我希望我的问题很清楚,如果不是,请告诉我.

可以或多或少地与此相提并论吗?

编辑:代码添加

我的抽象类看起来像:

public abstract class ExperimentPanelModel extends Panelizable {
protected String nextButtonText;
protected String backButtonText;
protected String skipButtonText;
protected Properties currentFile;
protected List<Properties> pastFiles = new ArrayList<Properties>();

public ExperimentPanelModel(Properties argcurrentfile,List<Properties> argpastfiles) {
    currentFile = argcurrentfile;
    pastFiles = argpastfiles;
    nextButtonText = "Next";
    backButtonText = "Back";
    skipButtonText = "Skip";
}
...
}

该抽象类的一些非抽象子类看起来像(注意它们都声明了公共静态最终字符串UNIQUE_ID):

public class ConfigurationGUI extends ExperimentPanelModel {

public static final String UNIQUE_ID = "ConfigurationGUI";
public static final String DATA_MODIFIED = "DataModified";

Date dateOfLastSession;
int ExperimentalSession;
int ExperimentOrder;

boolean nextButtonEnabled = false;

public ConfigurationGUI(Properties argcurrentfile,List<Properties> argpastfiles) {
    super(argcurrentfile,argpastfiles);
    nextButtonText = "Confirm";
    backButtonText = "Abort";
}

...
}

一个例子:

public class Introduction extends ExperimentPanelModel {

public static final String UNIQUE_ID = "Introduction";
public static final String INSTRUCTIONS_XML_FILE = "instructions.xml";
public static final String THIS_INSTRUCTION_PROPERTY = UNIQUE_ID;

private String thisInstructionText = UNIQUE_ID;

Properties readInstructionsproperties = new Properties();

public Introduction(Properties argcurrentfile,List<Properties> argpastfiles) {
 ...

最后一个

public class Instruction1 extends ExperimentPanelModel {

public static final String UNIQUE_ID = "Instruction1";
public static final String INSTRUCTIONS_XML_FILE = "instructions.xml";
public static final String THIS_INSTRUCTION_PROPERTY = UNIQUE_ID;
...
}

解决方法

字段构思不起作用,因为静态字段不能在子类中重写.你可以做的是你可以在抽象类上声明一个抽象方法,以便你的子类必须实现它.

另请注意,您无法将其设置为静态方法,因为这些方法也不会被覆盖.

原文地址:https://www.jb51.cc/java/127091.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐