The overcome PMD method called at object construction

I have the following structure

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 } } 

Could you advise how to solve this error?

+7
java pmd
source share
2 answers

PMD rule says:

Calling redefined methods during construction creates the risk of calling methods on an incompletely constructed object and can be difficult to debug. This can lead to the fact that the subclass will not be able to build its own superclass or is forced to completely reproduce the building process inside itself, having lost the ability to call super() . If the default constructor contains a call to an overridden method, the subclass can be completely irreversible. Note that this includes method calls throughout the control flow graph β€” that is, if the constructor Foo() calls the private method bar() , which calls the public method buz() , this means a problem.

Example:

 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(); } } 

Decision

Remove any call to overridden methods in the constructor or add the final modifier to these methods.

+12
source share

Perhaps you could follow the Java naming conventions as well as make the Child final class

 public final class Child extends Parent { 
+1
source share

All Articles