java抽象类中的变量,Java:如何在抽象类中引用子类的静态变量?

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;

}

}

解决方案

I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.

public abstract class AbstractModel {

public static ResultSet getAllFromTable(String tableName) {

Statement stmt = Database.get().conn.createStatement();

String query = "SELECT * FROM `" + tableName + "`";

return stmt.executeQuery(query);

}

}

public class Api extends AbstractModel {

protected static final String TABLE_NAME = "apis";

public static ResultSet getAll() {

return getAllFromTable(TABLE_NAME);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值