force subclasses to include constant in abstract java class

Viewed 11835

I have an abstract class, for which I want all 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?

6 Answers

Here is another approach. I like it because it is strict and lets us to place most of the code (includeing getters) into the parent class leaving its sublasses neat.

abstract class Parent {
    private final int age;
    private final String name;

    Parent(int age, String name) {
        this.age = age;
        this.name = name;
    }

    int getAge() {
        return age;
    }
}

class Child extends Parent {

    Child() {
        super(18, "John");
        // any other Child specific constructor logic
    }
}

class Main {
    public static void main(String[] args) {
        var child = new Child();
        System.out.println(child.getAge()); // Will print 18
    }
}

NOTE: Child does not inherit Parent's constructor and thus there is no danger of accidentally using the worng constructor when initializing Child.

Related