Difference between super() and this() in Java

Java Programming Java 8Object Oriented Programming

Following are the notable differences between super() and this() methods in Java.

 super()this()
Definitionsuper() - refers immediate parent class instance.this() - refers current class instance.
InvokeCan be used to invoke immediate parent class method.Can be used to invoke current class method.
Constructorsuper() acts as immediate parent class constructor and should be first line in child class constructor.this() acts as current class constructor and can be used in parametrized constructors.
OverrideWhen invoking a superclass version of an overridden method the super keyword is used.When invoking a current version of an overridden method the this keyword is used.

Example

 Live Demo

class Animal {
   String name;
   Animal(String name) {
      this.name = name;
   }
   public void move() {
      System.out.println("Animals can move");
   }
   public void show() {
      System.out.println(name);
   }
}
class Dog extends Animal {
   Dog() {
      //Using this to call current class constructor
      this("Test");
   }
   Dog(String name) {
      //Using super to invoke parent constructor
      super(name);
   }
   public void move() {
      // invokes the super class method
      super.move();
      System.out.println("Dogs can walk and run");
   }
}
public class Tester {
   public static void main(String args[]) {
      // Animal reference but Dog object
      Animal b = new Dog("Tiger");
      b.show();
      // runs the method in Dog class
      b.move();
   }
}

Output

Tiger
Animals can move
Dogs can walk and run
raja
Published on 13-Aug-2018 11:27:35
Advertisements