I want to define an abstract method like so:
public abstract class Saveable {
public Set<Field> getFieldSet();
...
}
getFields() should always return the same output regardless of the object’s state. However, I can’t declare this as a static method because I want it to be overridden. Now I’m implementing a class User which extends Saveable and it has some static methods which require the field set. Obviously, I can’t get it because I don’t have an object. Any idea on a design that would allow me to get the fields in a static method?
One approach would be “fake” the
thisreference by passing in an instance of the correct object to the static methods, and then callinggetFieldson that object.Another option is to store the field list in a static field on the class. Your overridden
getFields()implementation can return it (or preferably a copy of it,) and your static methods can access it directly.My preference would be to implement the latter option, as it’s a lot less clumsy (since you never have to new up an otherwise useless object to pass in to the static methods.) As well, it captures the idea that the class’s fields don’t rely on a given instance.