Java: Overriding static variable of parent class?

You cannot override static methods or fields of any type in Java.

public class User extends BaseModel
{
    static String table = "user";
    //snip
}

This creates a new field User#table that just happens to have the same name as BaseModel#table. Most IDEs will warn you about that.

If you change the value of the field in BaseModel, it will apply to all other model classes as well.

One way is to have the base methods generic

protected static boolean exists(String table, long id) throws Exception
{
    Db db = Util.getDb();
    Query q = db.query();
    q.select( idField ).whereLong(idField, id).limit(1).get(table);

    return q.hasResults();
}

and use it in the subclass

public static boolean exists(long id)
{
    return exists("user", id);
}

If you want to use the field approach, you have to create a BaseDAO class and have a UserDAO (one for each model class) that sets the field accordingly. Then you create singleton instances of all the daos.

Leave a Comment