1

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?

5
  • 5
    Don't ever have your superclass depend on its subclass(es). Commented Jul 6, 2016 at 22:17
  • 2
    If you need this behavior defined by data at the child level, make the method abstract and let the child class implement it. Commented Jul 6, 2016 at 22:19
  • i was trying to avoid this but looks like i might have to do what you said Commented Jul 6, 2016 at 22:19
  • The whole point of abstract methods is to defer implementation to the subclass, why wouldn't you want to do this? Commented Jul 6, 2016 at 22:20
  • Please accept Sotirios' comment as the answer to this question. If your super-classes are dependant on the behavior or structure of their subclasses, then something is very very wrong with your architecture and things WILL break/be unmaintainable. Commented Jul 6, 2016 at 22:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.