jonepatr
jonepatr

Reputation: 7809

Access sub class constant in static parent method

Is it possible to access a child class constant from within a static method in the parent class?

public class Model  {

    public static void someMethod(){
        HERE I WANT TO GET THE MODEL_NAME constant!
    }
}

public class EventModel extends Model {
    public static final String MODEL_NAME = "events";
}

and in some other place I call:

EventModel.someMethod();

Upvotes: 1

Views: 1420

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Try it!

If the constant is declared private, then no. If it is public, then yes, as anyone can access it. The parent class is largely irrelevent here.

class Parent {
    public static void Foo() {
        int x = Child.YEP;    // Ok
        int y = Child.NOPE;   // Error
    }
}

class Child extends Parent {
    public  static final int YEP  = 42;
    private static final int NOPE = 66;
}

Foo is defined in Parent, and thus cannot access private members of Child.

How about this?

class Parent {
    abstract String getModelName();

    public void someMethod() {
        String myModel = getModelName();
    }
}

class Child extend Parent {
    String getModelName() { return "events"; }
}

Note however, that the method is no longer public.

Upvotes: 3

XIVSolutions
XIVSolutions

Reputation: 4502

You might find this more effective.

Define your parent class with a method getName. Note that this can be public, if you want your model class to expose a Name property, otherwise, you can keep it as "protected" as I have here. "Protected" will keep the method visible within this class, and any derived (child) classes.

public class Model {
    private static String MODEL_NAME = "Model";

    protected String getModelName(){
        return MODEL_NAME;
    }       
}

Then define an "override" for the name method on your child class:

public class EventModel extends Model
{
    private static String MODEL_NAME = "events";

    @Override // Tells the compiler that this method OVERRIDES the parent method
    public String getModelName(){
        return MODEL_NAME;
    }
}

This compiles and runs the way I suspect you are trying to acheive . . .

EDIT: Oooh. NOW I see the problem. Missed that you needed to reference that from a static method . . .

Upvotes: 1

Related Questions