I have these two classes:
class Parent
{
protected static String table;
public static long getRow()
{
String query = "SELECT * FROM " + table + " WHERE id =? " ;
//other code...
}
}
I then extend this class :
class Child extends Parent
{
protected static String table = "tableName";
//other code..
}
However, when I try to do this:
long id = Child.getRow();
I get an error, because the query is getting “null” put in it where the value of table should be. I.e SELECT * FROM null.
I thought that setting the value of table in the child class would cause it to be updated in the methods it inherits as well, but apparently not. What do I need to do to fix this?
You cannot override variables this way. In your example, each class has its own version of the
tablevariable, and in the Parent, where thegetRowmethod is defined, the variable is undefined. Here’s a better design you can use: