Wednesday, March 30, 2022

this vs super in Java

 this vs super

  • this can be used to read all members declared within the class
  • this can all be used to read all inherited members in the direct parent class
  • this can be used in an instance method, constructor and instance block
  • this cannot be used in a static method or static initializer block
  • super can read only inherited members declared in the parent class
  • super excludes any members found in the current class
  • super always refer to the direct parent
  • this() can be used to invoke current class constructor
  • super() invokes constructor of the parent class
  • if we choose to call this() or super() , it must be the first statement in the constructor body. There can be only one call.
  • this refers to an instance of the class, while this() refers to a constructor call within the class
  • Java compiler automatically inserts a call to the no-argument constructor super() if we do not explicitly call this() or super() as the first line of a constructor.
  • static methods do not have reference to this or super

1 comment: