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

dei*_*rus 6 java inheritance static abstract-class

我有很多抽象类的子类,每个子类声明一个具有相同名称的公共静态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";
}
...
}
Run Code Online (Sandbox Code Playgroud)

该抽象类的一些非抽象子类看起来像(注意所有这些子类都声明public static final String 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";
}

...
}
Run Code Online (Sandbox Code Playgroud)

一个例子:

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) {
 ...
Run Code Online (Sandbox Code Playgroud)

最后一个:

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;
...
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 8

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

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