user2914191
user2914191

Reputation:

java parent access static variable of child

I have a parent class Table that is extended by children.

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.

Can this be done?

Upvotes: 1

Views: 1160

Answers (1)

Mshnik
Mshnik

Reputation: 7032

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. Having a static method in an abstract class that is intended to depend on what subclass it is doesn't actually make any sense.

Upvotes: 1

Related Questions