Search code examples
javainheritanceconstants

Abstract Java class: force subclasses to define a constant


I have an abstract class, for which I want all nonabstract subclasses to define a constant, based on the implementation—it is mainly metadata about the class implementation.

In the superclass:

protected static final String OBJECT_NAME;
protected static final String OBJECT_DEF;

And then in the subclass:

protected static final String OBJECT_NAME = "awesome class";
protected static final String OBJECT_DEF = "an awesome class that is also great";

Is there a way to force implementations of a class to declare a constant?


Solution

  • You can force sub-class to define a method which can be a constant for that class.

    protected abstract String objectName();
    protected abstract String objectDef();
    

    Note: if you have sub-class of your sub-classes, these might "forget" to override these methods.