DEV Community

Arun Kumar
Arun Kumar

Posted on

Difference between super() and this() in java

super and this keyword super() and this() keyword both are used to make constructor calls.

  • super() is used to call Base class's constructor(i.e, Parent's class).

  • this() is used to call the current class's constructor.

super() Keyword

super() is used to call Base class's(Parent class's) constructor.
Note: super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class's(super class's) constructor.

class Father{  
       Father(){
              System.out.println("Age of Father is 47");
 }  
}  
class Child extends Father{  
        Child(){  
               super();  
               System.out.println("Age of Child is 20");  
        }  
}  
class Example8{  
       public static void main(String args[]){  
              Child c=new Child();  
       }
}
Enter fullscreen mode Exit fullscreen mode

this() Keyword

this() is used to call the current class's constructor.
Note: this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only the current class's constructor.

class Student {
    String name;
    int age;

    // Constructor with 2 parameters
    Student(String n, int a) {
        name = n;
        age = a;
    }

    void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class ThisDemo {
    public static void main(String[] args) {
        Student s1 = new Student("Arun", 20);               s1.display();
    }
}

Enter fullscreen mode Exit fullscreen mode

Name: Arun, Age: 20
****Difference between super () and this ().

Reference
https://www.naukri.com/code360/library/difference-between-this-and-super-in-java
https://www.tutorialspoint.com/difference-between-super-and-this-in-java

Top comments (0)