4

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.

Nathan
  • 8,093
  • 8
  • 50
  • 76
  • Short answer is if you are extending anything other than Object, you want to give your parent object a chance to do any special initialization. – JustinKSU Feb 06 '19 at 22:59
  • 1
    Possible duplicate of [Why call super() in a constructor?](https://stackoverflow.com/questions/10508107/why-call-super-in-a-constructor) – JustinKSU Feb 06 '19 at 23:01
  • @JustinKSU The Java compiler will automatically add a call to the superclass constructor if there is no explicit call in the code, so your explanation makes no sense. Your duplicate also doesn't answer the question why PMD defines this rule. – Mark Rotteveel Feb 08 '19 at 18:51
  • This question is definitely not a duplicate of "Why call super() in a constructor?" – Nathan Feb 09 '19 at 19:53

1 Answers1

3

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?

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92