If a final subclass calls a superclass overridable method from the constructor, Spotbugs reports a bug (see note below for details).
Is this expected or is it an issue?
For example:
public class SuperClass {
private final int id;
public SuperClass(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public final class SubClass extends SuperClass {
private final String name;
public SubClass(int id, String code) {
super(id);
this.name = getId() code; // Spotbugs repot this line as a bug
}
public final String getName() {
return name;
}
}
Reports:
[ERROR] Low: Overridable method getId is called from constructor new SubClass(int, String).
[SubClass] At SubClass.java:[line ?] MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR
Note:
Since Spotbugs 4.5.0.0 bug detector FindOverridableMethodCall
was added (see details):
MC: An overridable method is called from a constructor
(MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR)Calling an overridable method during in a constructor may result in the use of uninitialized data. It may also leak the reference of the partially constructed object. Only static, final or private methods should be invoked from a constructor.
CodePudding user response:
This seems to be a bug, there is a recent open issue related to this case:
False positive for MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR in final class
There is also a pull request to fix this bug.