我有以下结构
public class parent {
int value ;
}
public class child extends parent {
int childValue;
public child(){}
public child (int value){
this.childValue = value ; // this line cause ConstructorCallsOverridableMethod warning during object construction
}
}
请问如何解决这个错误?
最佳答案
PMD rule说:
Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call
super()
. If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructorFoo()
calls a private methodbar()
that calls a public methodbuz()
, this denotes a problem.
例子:
public class SeniorClass {
public SeniorClass(){
toString(); //may throw NullPointerException if overridden
}
public String toString(){
return "IAmSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass(){
super(); //Automatic call leads to NullPointerException
name = "JuniorClass";
}
public String toString(){
return name.toUpperCase();
}
}
解决方案
删除构造函数中对可覆盖方法的任何调用或向该方法添加 final
修饰符。
关于java - PMD 对象构造期间调用的可覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504404/