I’m looking for a way to force subclasses to initialize parent class fields, like in this question.
I tried to implement accepted (and quite highly-voted) answer, but that raises Sonar complaint…
This is the code for future reference:
public abstract class SuperClass {
// Variable all inner classes must set
static int myVar = 0;
public SuperClass() {
myVar = giveValue();
}
public abstract int giveValue();
}
public class SubClass extends SuperClass {
@Override
public int giveValue() {
return 5; // individual value for the subclass
}
}
In this case calling overridable method is intentional. The rule explanation says “If the behavior of the child class method depends on fields that are initialized in the child class constructor”, but in this case I’m fully aware of the risk and I’m sure there won’t be the case - it’s kind of the other way.
Is it really bad design? I know I could just turn off this rule, but somehow feel bad about it…