My head hurts from thinking about an elegant solution to the following problem. I have a parent class and several subclasses. My parent class declares and implements a method to retrieve properties, but the name of the property file is determined by the subclasses.
I’m only working with instances of the subclasses.
The method (implemented in the parent) should use the field values of the subclass, but since I’m using it in the parent class, I need to declare it there as well.
Now, every time I call the method from a subclass the field value of the parent class is used.
Some simple code to illustrate my problem (please keep in mind: it’s not about functionality – more about the design). The subclass defining the field value I want to use:
public class SubClass extends Parent {
public static final String CONFIG_FILE = "subclass.properties"; // same problem with non-static
public SubClass() {
System.out.println(getProperty("somekey"));
}
}
and the parent class defining and implementing the method I want to use:
public class Parent {
public static final String CONFIG_FILE = "config.properties"; // same problem with non-static
public String getProperty(String key) {
Properties props = new Properties();
try {
props.load(new FileReader(new File(CONFIG_FILE)));
}
catch (IOException ioe) {
return null;
}
return props.get(key);
}
Since I’m calling getProperty(..) from the subclass, I would expect it to use the field value of the instance it is operating on (“subclass.properties”), but instead it’s using the parent field value (“config.properties”). I got the same effect with non-static fields.
Put this in your subclass. This will then return the properties for the subclass. This method would override the one in the parent class.
Incidently you are shadowing the variable.
Alternatively I would recommend passing in the variable name to the constructor and then have it call super.
and then have the Parent construtor something like
then you will not have to override the method. The method can just return config in the parent. I would think carefully as to whether you want it to be static though….