Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: can I require a child class to define a property value?

I have an abstract base class that many classes extend. I'd like all these classes to define a unique value for a specific property that is originally defined in the base class (similar to the serialVersionUID property that causes a warning when not defined in classes that inherit from Serializable).

Is there a way for me, within my abstract base class, to declare a property that does not have a value, but requires all extended classes to define a value for it?

Note that the value does not have to be associated with each individual instance, i.e.: it can be defined as static.

Edit: I guess a more basic question I should also ask, since the answers vary so widely, is how does Java implement serialVersionUID (in terms of its signature) such that my IDE raises warnings when it's not defined?

like image 604
Matt Huggins Avatar asked Aug 10 '10 21:08

Matt Huggins


1 Answers

Fields can not be overridden, but methods can. If you need not enforce that the value is constant, use:

class abstract Super() {
    /**
     * @return the magic value
     */
    abstract MyType getValue();
}

If you do need to enforce that the field is final, you can give each instance its own copy/reference as in the answers of Steve or Mike.

If you can't do that either you can do crazy stuff like:

class Super() {
    private static Map<Class<? extends Super, MyType> map = new ...;

    protected Super(MyType value) {
        if (!map.contains(getClass())) {
            map.put(getClass(), value);
        } else {
            assert map.get(getClass(), value) == value;
        }
    }
}
like image 183
meriton Avatar answered Sep 28 '22 05:09

meriton