Search code examples
javaconstructorsuperpmd

What is the reason for PMD CallSuperInConstructor?


PMD defines the rule CallSuperInConstructor. What is the purpose of adding a no-argument call to super() in the constructor when it is not required by the compiler?

I realize I could disable the rule or use @SuppressWarnings to silence the rule in each class.

This question deals with why one should call super(...) in a constructor. My question is about why one would add a no-argument super() call when the compiler does not require it.


Solution

  • If your class

    • has numerous overloaded constructors
    • is extending a non-Object class which has numerous overloaded constructors

    then when you explicitly call super() it avoids confusion which class/superclass constructor is called.

    An example illustrating the above:

    class Foo {
        final int x;
        Foo(int x) {
            this.x = x;
        }
        Foo() {
            this.x = 1;
        }
    }
    
    class Bar extends Foo {
        Bar(int x) {
        }
    }
    

    Question - what is the value of new Bar(10).x?