简体   繁体   English

java子级父级访问静态变量

[英]java parent access static variable of child

I have a parent class Table that is extended by children. 我有一个由孩子扩展的父类Table

Parent Class: 家长班:

abstract class Table{

    public static String getFullTable(){
        return child.DBTABLE + '.' + child.DBNAME;
    }

}

A Sample Table 样品表

class User extends Table{
    public static final String DBTABLE = "user";
    public static final String DBNAME = "test";
}

When calling User.getFullTable() I want to retrieve the value test.user . 调用User.getFullTable()我想检索值test.user

Can this be done? 能做到吗?

Add abstract methods that request the information from the child class, as such: 添加从子类请求信息的抽象方法,例如:

abstract class Table{

    protected abstract String getDBTable();
    protected abstract String getDBName()

    public String getFullTable(){
        return getDBTable() + '.' + getDBName();
    }

}

class User extends Table{
    public static final String DBTABLE = "user";
    public static final String DBNAME = "test";

    protected String getDBTable() {
        return DBTABLE;
    }

    protected String getDBName() {
        return DBNAME;
    }
}

It's worth noting that I changed getFullTable() to be non-static. 值得注意的是,我将getFullTable()更改为非静态的。 Having a static method in an abstract class that is intended to depend on what subclass it is doesn't actually make any sense. 在抽象类中有一个静态方法要依赖于它的子类,这实际上没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM