Java:覆盖父类的静态变量? [英] Java: Overriding static variable of parent class?

查看:460
本文介绍了Java:覆盖父类的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程,我正在使用它作为我项目中所有模型的基础:

I have the following class which I'm using as the base of all the models in my project:

public abstract class BaseModel
{
    static String table;
    static String idField = "id";       

    public static boolean exists(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();
    }

    //snip..
}



<然后我尝试通过以下方式扩展它:

I'm then trying to extend from it, in the following way:

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

但是,如果我尝试执行以下操作:

However, if I try to do the following:

if ( User.exists( 4 ) )
   //do something

然后,而不是查询:SELECT id FROM user WHERE id =?,它产生查询:SELECT id from null WHERE id =?。因此,覆盖用户类中的字段似乎没有任何效果。

Then, rather than the query: "SELECT id FROM user WHERE id = ?", it is producing the query: "SELECT id from null WHERE id = ?". So, the overriding of the table field in the User class doesn't seem to be having any effect.

我如何克服这个问题?如果我向BaseModel添加了一个 setTable()方法,并在<$ c $的构造函数中调用了 setTable() c>用户,然后的新值可用于用户类?

How do I overcome this? If I added a setTable() method to BaseModel, and called setTable() in the constructor of User, then will the new value of table be available to all methods of the User class as well?

推荐答案

您不能在Java中覆盖任何类型的静态方法或字段。

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

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

这会创建一个新字段 User#table 恰好与 BaseModel#table 具有相同的名称。大多数IDE会警告你。

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.

如果更改BaseModel中字段的值,它也将适用于所有其他模型类。

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();
}

并在子类中使用它

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

如果你想使用现场方法,你必须创建一个 BaseDAO 类并且具有 UserDAO (每个模型类一个),相应地设置字段。然后你创建所有daos的单例实例。

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.

这篇关于Java:覆盖父类的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆