I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.
The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.
But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.
What's the best solution here? I'd rather not put nearly identical instances of getAll
in every subclass.
public abstract class AbstractModel {
public abstract String getTableName();
public static ResultSet getAll() {
Statement stmt = Database.get().conn.createStatement();
// Error below: Cannot use "this" in static context.
String query = "SELECT * FROM `" + this.getTableName() + "`";
return stmt.executeQuery(query);
}
}
public class Api extends AbstractModel {
protected static final String TABLE_NAME = "apis";
@Override
public String getTableName() {
return TABLE_NAME;
}
}