dabadaba dabadaba - 6 months ago 11
Java Question

How to initialize static member in child class?

Let's say we have an abstract class that defines a constructor taking an integer where a precondition checks if the integer is within a list of possible values:

public abstract class Value {
protected int value;
protected static List<Integer> possibleValues;

public Value(int val) {
if (!possibleValues.contains(val))
throw new IllegalArgumentException("Illegal value");
value = val;
}
}


But we want to initialize that list in
Value
's child classes because each define their own list of possible values.

I guess I could do a
static
block adding members to
possibleValues
, although I dislike
static
blocks. But that does not mean that all child classes would stop pointing to the same list of possible values.

How can I force the child classes to define a list of possible values and do the precondition check without facing the issues I described?

Edit: so we could say I want to inherit the behavior but not the variable itself.

Answer

How about:

public abstract class Value {
   protected int value;
   protected abstract List<Integer> getPossibleValues();

   public Value(int val) {
       if (!getPossibleValues().contains(val))
           throw new IllegalArgumentException("Illegal value");
       value = val;
   }
}

Your subclasses will be forced to implement getPossibleValues().

Comments