Search code examples
javasuper

Java. Super call in class which extends Object


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().


Solution

  • 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".