Difference between super() and this() in Java



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

  super() this()
Definition super() - refers immediate parent class instance. this() - refers current class instance.
Invoke Can be used to invoke immediate parent class method. Can be used to invoke current class method.
Constructor super() 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.
Override When 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
Updated on: 2020-06-21T12:42:48+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements