Open In App

Difference between super() and this() in java

Last Updated : 09 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

super and this keyword super() as well as this() keyword both are used to make constructor calls. super() is used to call Base class’s constructor(i.e, Parent’s class) while this() is used to call the current class’s constructor. Let us see both of them in detail:

super() Keyword 

super() is used to call Base class’s(Parent class’s) constructor

Java




// Java program to illustrate usage of
// this() as first statement
  
class RR {
    RR()
    {
        // Uncommenting below line causes compilation
        // error because this() should be first statement
        // System.out.println("Compile Time
        // Error");
        this(51);
        System.out.println(
            " Flow comes back from RR & quot; + "
            class 1 arg const& quot;);
    }
    RR(int k)
    {
        System.out.println("RR class's 1 arg const");
    }
    public static void main(String[] args)
    {
        new RR();
        System.out.println(" Inside main & quot;);
    }
}


Output:

Parent class's No arg constructor
Flow comes back from Parent class no arg const
Inside Main

Flow of Program:

  • In main, we have made a statement new Child(), so it calls the no argument constructor of Child class.
  • Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor.
  • Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const.
  • Further after completing the no-argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main.

We can use super() only inside constructor and nowhere else, not even in static context not even inside methods and super() should be first statement inside constructor. 

Java




// Java program to illustrate super() by default
// executed by compiler if not provided explicitly

class Parent {
Parent()
{
System.out.println(“Parent class’s No ” +
“argument constructor”);
}
Parent(int a)
{
System.out.println(“Parent class’s 1 argument” +
” constructor”);
}

}

class Base extends Parent {
Base()
{
// By default compiler put super()
// here and not super(int)
System.out.println(“Base class’s No ” +
“argument constructor”);
}
public static void main(String[] args)
{
new Base();
System.out.println(“Inside Main”);
}
}


Output:

Parent class's No arg constructor
Flow comes back from Parent class no arg const
Inside main

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.

this() Keyword 

this() is used to call the current class’s constructor

Java




// Java program to illustrate recursive
// constructor call not allowed
 
class RR {
    RR() { this(30); }
    RR(int a) { this(); }
    public static void main(String[] args) { new RR(); }
}


Output:

RR class's 1 arg const
Flow comes back from RR class's 1 arg const
Inside Main

Flow of Program:

  • First, start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of the current class(i.e, RR class)
  • Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that, we have an SOP statement and hence it prints RR class’s 1 arg const.
  • Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const.
  • Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main.

We can use this() only inside constructor and nowhere else, not even in static context not even inside methods and this() should be first statement inside constructor. 

Java





Output:

RR class's 1 arg constructor
Flow comes back from RR class 1 arg const
Inside main

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.

Important points about this() and super()

  1. We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both.
  2. It is up to you whether you use super() or this() or not because if we are not using this() or super() then by default compiler will put super() as the first statement inside the constructor. 

Example

Java




// Java program to illustrate super() by default
// executed by compiler if not provided explicitly
  
class Parent {
    Parent()
    {
        System.out.println("Parent class's No " +
                          "argument constructor");
    }
    Parent(int a)
    {
        System.out.println("Parent class's 1 argument" +
                                      " constructor");
    }
  
}
  
class Base extends Parent {
    Base()
    {
        // By default compiler put super()
        // here and not super(int)
        System.out.println("Base class's No " +
                        "argument constructor");
    }
    public static void main(String[] args)
    {
        new Base();
        System.out.println("Inside Main");
    }
}


Output:
Parent class's No argument constructor
Base class's No argument constructor
Inside Main

Flow of program:

  • Inside main we have new Base() then flow goes to No argument constructor of Base class.
  • After that, if we don’t put either super() or this() then by default compiler put super().
  • So flow goes to Parent class’s No arg constructor and not 1 argument constructor.
  • After that, it prints Parent class’s No argument constructor.
  • After that when Parent() constructor completes the flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor.
  • After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside main

Recursive constructor call not allowed 

Java




// Java program to illustrate recursive
// constructor call not allowed
 
class RR {
    RR() { this(30); }
    RR(int a) { this(); }
    public static void main(String[] args) { new RR(); }
}


Output:

Compile time error saying recursive constructor invocation

Flow of program: Here, above starts from main() and then flow goes to No arg constructor of RR class. After that, we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on …… like a recursion. So it is invalid that’s why we get a compile-time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java.

Let us see the differences in a tabular form as follows:

super() keyword this() keyword 
super() calls the parent constructor this() can be used to invoke the current class constructor
It can be used to call methods from the parent. It can be passed as an argument in the method call.
It is returned with no arguments. It can be passed as an argument in the constructor call.
It can be used with instance members. It is used to return the current class instance from the method.



Similar Reads

Difference between super and super() in Java with Examples
In java it is predefined that the 'super' word is somewhere related to the parent class. If we need to brief and justify the title in one go then the super keyword in java refers to dealing with parent class object while super() deals with parent class constructor. We will be covering the article first discussing the concept of a super keyword foll
4 min read
Access Super Class Methods and Instance Variables Without super Keyword in Java
A class describes the property and the attributes of the object. A class contains mainly includes the following components. Modifiers: The keywords in java which provide a set of restriction on the class and its members and methods.Class keyword: The initialization of the class is done by class reserved word and following by the name of the class.C
3 min read
Difference between Super Key and Candidate Key
Super Key: Super Key is an attribute (or set of attributes) that is used to uniquely identifies all attributes in a relation. All super keys can’t be candidate keys but the reverse is true. In relation, a number of super keys is more than a number of candidate keys. Prerequisite - Keys in Relational Model Example: We have a given relation R(A, B, C
2 min read
Difference between Primary key and Super key
Prerequisite - Keys in Relational Model 1. Super Key: Super Key is an attribute (or set of attributes) that is used to uniquely identifies all attributes in a relation. All super keys can’t be candidate keys but its reverse is true. In a relation, number of super keys are more than number of candidate keys. Example: We have a given relation R(A, B,
2 min read
Difference between Super Computers and Embedded Computers
1. Super Computers :Super Computers, as name suggests, are specialized computer system that is built to perform difficult calculations much quickly and therefore considered most important tool for researches. It is better technological tool for complex large-scale computing tasks with high level of performance.Examples : Tianhe-1, Kraken, Jugene, e
2 min read
Java Program to Allocate and Initialize Super Class Members Using Constructor
A constructor in Java is a special method that is used to initialize an object. Whenever an object is created using the new keyword at least one construction is called. The constructor name must match with the class name and cannot have a return type. If there is no constructor available in the class in such a case java compiler provides a default
4 min read
super and this keywords in Java
In java, super keyword is used to access methods of the parent class while this is used to access methods of the current class. this keyword is a reserved keyword in java i.e, we can't use it as an identifier. It is used to refer current class's instance as well as static members. It can be used in various contexts as given below: to refer instance
7 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
Java Program to Illustrate the Availability of Default Constructor of the Super Class to the Sub Class by Default
A constructor in Java is a special method that is used to initialize an object. Whenever an object is created using the new() keyword at least one construction is called. The constructor name must match with the class name and cannot have a return type. If there is no constructor available in the class in such a case java compiler provides a defaul
5 min read
Article Tags :
Practice Tags :