educative.io

Educative

Using super() and this() in a constructor

A reader asked us the following question:

Hello, This page says: “Note: In a constructor we can include a call to super() or this() but not both. Also, these calls can only be used inside the constructors.” However, on lines 30 and 31 of the second code example, you use both super() and this() inside a constructor. How is this consistent? Am I missing something? Thank you

Hi,

This is Fatimah Abdullah from Educative. I noticed your feedback here and I’m glad you reached out to us.

In response to your question, the note that you have quoted is referring to the super() and this() functions. The super() is used to call the constructor of the parent class inside the constructor of the child.

Usage of super() :

class Parent { 
    Parent(int n) 
    { 
       ...
    } 
}  
class Child extends Parent { 
    Child(int n) 
    { 
        super(n); // calls the Parent(int n) function
        ...
    } 
}

Whereas, the this() function is used to call another constructor of the same class (in case there are multiple constructors with different parameters).

Usage of this() :

class Child {
    Child(int n) 
    { 
        this(); // calls the Child() function
        ...
    }
    Child(){
        ...
    }
}

Now that we have that cleared out, the code example you are referencing has the following statements on lines 30 and 31:

super(make, color, year, model);  //parent class constructor
this.bodyStyle = bodyStyle;

Here, super() is used inside the constructor to call the constructor of parent. However, in the next line, this() function is not used, it is not a function call. Here, this is a keyword that is used as a reference to the object of the current class. Think of this as an alias for the name of the object on which the function call was made.
Usage of this :

class Person {    
    int name;    
    Student(int name)​ ​{ 
        this.name = name;   
    } 
}

I hope that my explanation helped clear the doubts you had. If you have anymore questions please feel free to get in touch!

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative Inc.

2 Likes