我有这两门课:
class Parent
{
protected static String table;
public static long getRow()
{
String query = "SELECT * FROM " + table + " WHERE id =? " ;
//other code...
}
}
然后我扩展这个类:
class Child extends Parent
{
protected static String table = "tableName";
//other code..
}
但是,当我尝试这样做时:
long id = Child.getRow();
我收到错误,因为查询将“null”放入其中 table
值应有的位置。即SELECT * FROM null
。
我认为在子类中设置table
的值会导致它在它继承的方法中也被更新,但显然不是。我需要做什么来解决这个问题?
最佳答案
您不能以这种方式覆盖变量。在您的示例中,每个类都有自己的 table
变量版本,而在定义了 getRow
方法的父级中,该变量未定义。您可以使用以下更好的设计:
abstract class Parent {
public abstract String getTable();
public static long getRow() {
String query = String.format("SELECT * FROM %s WHERE id = ?", getTable()) ;
//other code...
}
}
class Child extends Parent {
public String getTable() {
return "tableName";
}
}
关于java - Java中如何覆盖子类中Super对象的某个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14803690/