2013-03-11 90 views
6

我有很多抽象类的子类,并且它们中的每个都声明具有相同名称的公共静态最终字段。我正在考虑在抽象超类中拥有这个字段而没有初始化它,并希望每个子类都被迫初始化它。抽象类或接口中的公共静态最终字段

我在想这个,因为抽象类的所有子类都声明了一个名为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"; 
} 
... 
} 

一些抽象类样子的非抽象子类(请注意,所有这些声明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"; 
} 

... 
} 

一个例子更多:

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; 
... 
} 
+1

请添加片段代码,使这个问题更清晰! – ppeterka 2013-03-11 16:51:13

+1

发布一些代码请 – 2013-03-11 16:51:27

+1

希望我的回答是有帮助的。不确定是否有比当前实施更好的快速修复。从长远来看,从静态字段转移到跟踪元数据的单独数据结构可能是一种改进。 – 2013-03-15 14:37:37

回答

8

领域的想法是行不通的,因为静态字段不能在子类中重写。你可以做的是你可以在抽象类上声明一个抽象方法,以便你的子类必须实现它。

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

1

将公共最终字段UNIQUE-ID放入抽象类并声明一个受保护的构造函数,该构造函数接受UNIQUE-ID的值。您将无法将其设置为静态,因为对于不同的实例,值需要不同。

+0

上面的答案好多了:-) – GHC 2013-03-11 17:00:23

3

在你的情况下,我会在祖先中定义变量。在每个扩展类中都没有变量,除非你有一个特别好的理由,而你听起来并不像这样。

对于Nathan的回复+1。在很多情况下,这是一件更好的事情。

+0

谢谢,我读到这个问题意味着该字段必须在每个子类中采用不同的值。这个问题并不十分清楚。 – 2013-03-11 17:54:44

+0

是的,问题是没有很好的公式化。 – carlspring 2013-03-11 19:42:53

+0

弥敦道休斯阅读正确。我刚刚添加了一些代码,我希望现在更清楚。 – deinocheirus 2013-03-12 10:30:01