2

I often see the code like this:

class MyClass{
      private int a;
      public MyClass(int a){
           super();        //what is the purpose of this method call?
           this.a = a;
      }
      //other class methods here
}

If class extends object, super() call invokes Object constructor which, as I know, does nothing. Then why it's needed to call super()? I'm interested in that particular case, when super() does nothing because it just calls Object().

krund
  • 740
  • 1
  • 7
  • 16
  • 2
    I hope you understand, the call to `super()` is optional. Good practice, but if it doesn't serve any purpose to you, you can skip it. – Naman Dec 11 '16 at 10:37
  • Tastes differ. FWIW, my personal style is I write an explicit super call to remind myself and the reader that a super constructor is called, *except* if the super class is `Object` since I believe everyone knows the `Object()` constructor is eventually called and I don’t think a reminder about this fact is worth it. – Ole V.V. Dec 11 '16 at 11:00
  • @OleV.V. As it is redundant I would expect an experienced programmer to be puzzled why the call is there. Do you add a comment too? – Thorbjørn Ravn Andersen May 23 '19 at 17:48
  • Hahaha, @ThorbjørnRavnAndersen, I liked that. No, I add no comment when calling `super()`. – Ole V.V. May 23 '19 at 18:27
  • 1
    @OleV.V. In that case, if I was to peer review your code I would ask you to remove it. – Thorbjørn Ravn Andersen May 24 '19 at 06:42

1 Answers1

0

First of all I recommend reading the source - documentation. Then a quote of jb-nizet's answer:

Note that this explicit call is unnecessary since the compiler would add it for you. You only need to add a super() call in a constructor when you want to invoke a superclass constructor with arguments.

In Java, super refers to the parent class. We can use it in two ways:

super() is calling the constructor of the parent class. super.toString() will call the parent class' implementation of toString method.

In your example:

class MyClass{
      private int a;
      public MyClass(int a){
           super();        //what purpose of this?
           this.a = a;
      }
      //other class methods here
}

it's calling the constructor of Object which is blank, so it's just being pedantic, but if we modify it:

class Foo extends Bar{
      private int a;
      public Foo(int a){
           super();        //what purpose of this?
           this.a = a;
      }
      //other class methods here
}

it stands for calling Bar's constructor first.

Another usage which I have earlier described is:

class Bar {
    public String toString() {
        return "bar";
    }
}

class Foo extends Bar{
      String foo = "foo";
      public Foo(){
           super();        //what purpose of this?
      }
      public String toString() {
          super.toString()
}

will result in returning "bar".

Community
  • 1
  • 1
xenteros
  • 15,586
  • 12
  • 56
  • 91