Which keyword is used to call parent class constructor and method from within the child class

Accessing Superclass Members

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

Subclass Constructors

The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:

public MountainBike(int startHeight, 
                    int startCadence,
                    int startSpeed,
                    int startGear) {
    super(startCadence, startSpeed, startGear);
    seatHeight = startHeight;
}   

Invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

or:

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.


Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.


If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

Learn about This and Super Keyword in Java.

Abstract

The this and super are reserved keywords in Java. The super keyword is used to represent an instance of the parent class and can invoke constructor of the parent class durning inheritance, whereas the this keyword is used to represent an instance of the current class, also this keyword is used to refer the static members as well as invoke constructor of the current class.

Scope of the Article

  • The article will explain this and super keyword used in Java Programming.
  • Examples using this and super keyword.
  • Differences and similarities between this and super keyword in Java.

Introduction

Java provides many implicit keywords among those “this” and “super” are two reference variables. “this” and “super” are used to resemble the reference variable pointing to sub-class or parent class (superclass).

this: this is the reserved keyword in Java that is used to invoke constructor, methods, static members of the current class.

super: super is the reserved keyword in Java that is used to invoke constructor, methods of the parent class. This is possible only when one class inherits another class(child class extends parent class).

What is this keyword in Java?

class Code{
    int var;
    void method(int var){
        this.var = var;
    }
}

Let us under the use of this keyword using the above code snippet. As we can see that we have a variable 'var' and a parameter 'var' inside the method function. If we want to assign the value of parameter 'var' to the variable 'var' inside the class then we have to use the this keyword. In technical terms we are using this keyword tw refer the instance of current class.

this” is a special keyword in Java that is used to refer to the instance of the current class. Using the “this” keyword, we can refer to the current class's methods, constructor, instance variables, and many more. We cannot use the “this” keyword as an identifier in Java(identifier is name given to any method, class, package, etc.).

Uses of “this” keyword in Java

  • It can be passed as an argument in the method call.
  • It can be used to return the current class instances.
  • It refers to an instance variable and static variable of the current class.
  • It can be passed as an argument in the constructor call.
  • It is used to initiate a constructor of the current class.

Example of this keyword in Java

Example 1

The “this” keyword is referring to an instance and a static variable in the same class. By this we can change the values of the variables that are declared inside the class. Also we can differentiate between the variables that are declared inside the classes and methods.

// Illustration class
class Illustration{
	// declaring an instance variable
	int instanceVar = 5;

	// declaring an static variable
	static int staticVar = 10;

	void Scaler(){
		int instanceVar = 20;
		// referring to the current class instance variable
		this.instanceVar = 50;

		int staticVar = 40;
		// referring to the current class static variable
		this.staticVar = 100;

		// printing the current class instance and static variable.
		System.out.println("Value of instance variable : "+this.instanceVar);
		System.out.println("Value of static variable : "+this.staticVar);
		System.out.println("Value of variables declared inside method : "+instanceVar+" "+staticVar);
	}
}
public class main {
    public static void main(String[] args) {
    	// creating an instance of Illustration class
    	Illustration obj = new Illustration();
    	obj.Scaler();
    }
}

Output:

Value of instance variable : 50
Value of static variable : 100
Value of variables declared inside method : 20 40

Explanation:

In the above example, the instanceVar is an instance variable, and the staticVar is a static variable inside the class. Both the variables are referred in the "Scaler" method by using the "this" keyword. instanceVar is initialized with value 5, and staticVar is initialized with value 10. The scaler method reinitializes the instanceVar and staticVar using the "this" keyword with 50 and 100, respectively. There are other two variables having same name as static variables. We are able to differentiate between variables inside the class and methods by using this keyword.

Example 2

The “this” keyword is used to invoke current class method. Instead of calling all the methods of class differently inside the main class we can use this keyword, so that all the methods can be executed using a single call.

// Illustration class
class Illustration{
	// current class method
	void scaler(){
	    System.out.print("My name is : ");
	}
	void name(){
        // invoking current class scaler method.
            this.scaler();
	    System.out.println("Soham.");
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating an instance of Illustration class
    	Illustration obj = new Illustration();
    	obj.name();
    }
}

Output:

Explanation:

In the above example, the Illustration class has two methods scaler and name. The scaler method is invoked inside the name method by using the “this” keyword. To call the scaler method, we don't need to write writing obj.scaler() instead we can call it inside name function using this keyword.

Example 3

The “this” keyword is used to invoke the constructor of the current class. Suppose a class has two constructor one is no argument constructor and another is parameterized constructor. So for invoking both the constructors by a single call is can be done using a this keyword.

// Illustration class
class Illustration{
	// simple constructor
	Illustration(){
		// invoking parameterized constructor
		this(10);
	}

	// parameterized constructor
	Illustration(int x){
		System.out.println("Current class parameterized constructor invoked.");
		System.out.println("Number is : "+x);
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating an instance of Illustration class
    	Illustration obj = new Illustration();
    }
}

Output:

Current class parameterized constructor invoked.
Number is : 10

Explanation:

In the above example, there are two constructors. The no argument constructor is called while creating the object, and the parameterized constructor is called within the no argument constructor by using the “this” keyword. current class method.

Example 4

The “this” keyword is used to pass an argument in the method. At industry level it is used in event handlers or at places where we have to provide reference of one class to another class.

// Illustration class
class Illustration{
	// print method
	void print(Illustration ob){
		System.out.println("Method is invoked.");
	}
	void invoke(){
		// print method is invoked by passing this as an argument
		print(this);
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating an instance of Illustration class
    	Illustration obj = new Illustration();
    	obj.invoke();
    }
}

Output:

Explanation:

In the above example, we are passing the “this” keyword as an argument to call the print method in the invoke method.

Example 5

The “this” keyword is used to pass as an argument in the constructor call. By passing this as an argument in the constructor call we can exhange data from one class to another. This makes exchange of data between multiple classes a lot easier.

// A class
class A{
	// instance variable
	B tmp;
	// parameterized constructor
	A(B tmp){
		this.tmp = tmp;
	}
	// print method
	void print(){
		System.out.println("The number is : "+tmp.val);
	}
}
// B class
class B{
	// instance variable
	int val = 50;
	// constructor
	B(){
		// creating instance of A
		// passing “this” as an argument in constructor call
		A obj = new A(this);
		obj.print();
	}
}
public class Main {
    public static void main(String[] args) {
    	B b = new B();
    }
}

Output:

Explanation:

In the above example, we have passed the "this" keyword as an argument in the constructor call. Here A and B are two classes; parameterized constructor of A is called in class B by creating an object of class A and passing "this" as a parameter.

Example 6

The “this” keyword is used to return the current class instance. Methods of the class can be called directly at the time of creating an object.

// illustration class
class Illustration{
	Illustration getIllustration(){
		// returing the instance of current class
		return this;
	}
	void print(){
		System.out.println("Hello World!");
	}
}
public class Main {
    public static void main(String[] args) {
    	new Illustration().getIllustration().print();
    }
}

Output:

Explanation:

In the above example, the getIllustration method returns the current class instance and through which we called the print method.

What is a “super” keyword in Java?

class A{
    void methodP(){
        // method
    }
}
class B extends A{
    void methodC(){
        // method
    }
}
class C extends B{
    void methodGC(){
        // method
    }
}

Let me explain the term immediate parent. In the above code snippet of multi-level inheritance class B extends class A, it implies class A is immediate parent of class B. Similarly class C extends class B and now class C has two parents i.e., class A and class B, where class B is immediate parent of class C.

What is used wants to use the methods of class A in class B? We solve this issue using the super keyword.

super” is a special keyword in Java that is used to refer to the instance of the immediate parent class. Using the “super” keyword, we can refer to the immediate parent class's methods, constructor, instance variables, and many more. We cannot use the “super” keyword as an identifier in Java.

Uses of “super” Keyword in Java

  • It is used to refer to an instance variable of an immediate parent class.
  • It is used to invoke a method of an immediate parent class.
  • It is used to invoke a constructor of an immediate parent class.

Examples of “super” Keyword in Java

Example 1

The “super” keyword is used to refer to an instance variable of an immediate parent class.

// parent class
class Parent{
	int a = 50;
	String s = "Hello World!";
}
// child class extending parent class
class Child extends Parent{
	int a = 100;
	String s = "Happy Coding!";
	void print(){
		// referencing to the instance variable of parent class
		System.out.println("Number from parent class is : "+super.a);
		System.out.println("String from parent class is : "+super.s);

		// printing a and s of the current/child class
		System.out.println("Number from child class is : "+a);
		System.out.println("String from child class is : "+s);
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating instance of child class
    	Child obj = new Child();
    	obj.print();
    }
}

Output:

Number from parent class is : 50
String from parent class is : Hello World!
Number from child class is : 100
String from child class is : Happy Coding!

Explanation:

In the above example, the child class extends the parent class. Both have two instance variables, a and s. In child class, the print method calls the instance variables of the parent class using the "super" keyword. In comparison, the instance variables of child class don't need one. It doesn't matter whether the instance variable of parent class and child class share the same name; they can hold different values and are not overridden.

Example 2

The “super” keyword is used to invoke an immediate parent class method.

// parent class
class Parent{
	// declaring display method parent class
	void display(){
		System.out.println("Hi i am parent method.");
	}
}
// child class extending parent class
class Child extends Parent{
	// declaring display method in Child class
	void display(){
		System.out.println("Hi i am child method.");
	}
	void print(){
		// invoking display method from parent class
		super.display();
		// display method from child class
		display();
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating instance of child class
    	Child obj = new Child();
    	obj.print();
    }
}

Output:

Hi i am parent method.
Hi i am child method.

Explanation:

In the above example, child class extends parent class. Both have a display method. The print method in the child class invokes the display method of the parent class by using the “super” keyword. The example says that to invoke the methods in the child class from the parent class, we must use the “super” keyword.

Example 3

The “super” keyword is used to invoke an immediate parent class constructor.

// parent class
class Parent{
	// parent class constructor
	Parent(){
		System.out.println("Hi I am Parent class constructor.");
	}
}
// child class extending parent class
class Child extends Parent{
	// child class constructor
	Child(){
		// invoking parent class constructor
		super();
	}
}
public class Main {
    public static void main(String[] args) {
    	// creating instance of child class
    	Child obj = new Child();
    }
}

Output:

Hi I am Parent class constructor.

Explanation:

In the above example, the child class extends parent class. While creating an object of the child class, the constructor of the child class is called, where the parent class constructor is invoked using the “super” keyword.

Difference Between this and super Keyword in Java

"this" keyword in Java"super" keyword in Java
1. "this" is an implicit reference variable keyword used to represent the current class. 1. "super" is an implicit reference variable keyword used to represent the immediate parent class.
2. “this” is to invoke methods of the current class. 2. “super” is used to invoke methods of the immediate parent class.
3. “this” is used to invoke a constructor of the current class. 3. “super” is used to invoke a constructor of the immediate parent class.
4. “this” refers to the instance and static variables of the current class. 4. “super” refers to the instance and static variables of the immediate parent class.
5. "this" can be used to return and pass as an argument in the context of a current class object. 5. "super" can be used to return and pass as an argument in the context of an immediate parent class object.

Similarities Between “this” and “super” Keyword in Java

  1. Both "this" and "super" are non-static, so they can't be used in static areas. It means that we cannot use both the keywords in the main function in Java.

Example 1

public class Main {
	int a = 50;
    public static void main(String[] args) {
    	System.out.println(this.a);
    }
}

Output:

Main.java:4: error: non-static variable this cannot be referenced from a static context
    	System.out.println(this.a);

Explanation:

In the above example, we are referencing the non-static variable "this" in the static context. This led to a compiler error.

  1. Both “super” and “this” keywords in Java can be used in constructor chaining to call another constructor. “this()” calls the no-argument constructor of the current class, and “super()” calls the no-argument constructor of the parent class.

Example 2

// declaring parent class
class Parent{
	Parent(){
		System.out.println("Parent class no argument constructor");
	}
	Parent(String s){
		System.out.println("Parent class parameterized "+s);
	}
}
// Child class extends parent class
class Child extends Parent{
	Child(){
		// referring current class parameterized constructor
		this("constructor.");
		System.out.println("Child class no-argument constructor.");
	}
	Child(String s){
		// referring parent class parameterized constructor
		super("constructor.");
		System.out.println("Child class parameterized "+s);
	}
}
public class Main {
    public static void main(String[] args) {
    	// instance of child class
    	Child obj = new Child();
    }

Output:

Parent class parameterized constructor.
Child class parameterized constructor.
Child class no-argument constructor.

Explanation:

In the above example, we first forward a call from the child class no-argument constructor to the child class parameterized constructor using the "this" keyword. We are forwarding a call to the parent class parameterized constructor using the "super" keyword from a child class parameterized constructor.

  1. “this” and “super” must be the first statement if used inside the constructor. This means we cannot call both statements in a single constructor.

Example 3

// declaring parent class
class Parent{
	Parent(){
		System.out.println("Parent class no argument constructor");
		this.("constructor.");
	}
	Parent(String s){
		System.out.println("Parent class parameterized "+s);
	}
}
public class Main {
    public static void main(String[] args) {
    	// instance of child class
    	Parent obj = new Parent();
    }
}

Output:

Main.java:5: error: call to this must be first statement in constructor
		this("constructor.");
		    ^
1 error

Explanation:

In the above example, the error will be displayed as shown in output because the "this()" statement is not executed first.

Can we Use Both this() and super() in the Same Constructor?

No, we cannot use the “this()” and “super()” in the same constructor. If we want to use “this()” or “super()” inside a constructor, they must be written (executed) at first. Both “this()” and “super” cannot be executed simultaneously, hence “this()” and “super()” in Java cannot be used in the same constructor.

Important Points About this() and super() in Java

  • this()” as well “super()” can be used exactly once inside the constructor.
  • If we use “this()” followed by “super()” or “super()” followed by “this()” we will get compile-time error as. Either “this()” or “super()” can be the first statement inside the constructor, not both.
  • Inside the constructor, we cannot call the “this()” and “super()” recursively. Example

    // declaring parent class
    class A{
        A(){
            this(" ");
            System.out.println("No argument constructor");
        }
        A(String s){
            this();
            System.out.println("Parameterized constructor");
        }
    }
    public class Main {
        public static void main(String[] args) {
            // instance of child class
            A obj = new A();
        }
    }
    

    Output

    Main.java:3: error: recursive constructor invocation
        A(){
        ^
    1 error
    

    In the above example, we have recursively made calls for the constructor, which leads to a compile-time error.

Conclusion.

  • super” and “this” in Java are two predefined keywords, that cannot be used as an identifier.
  • super” in Java is used to refer to methods, static and instance variables, constructors of an immediate parent class.
  • this” in Java is used to refer to methods, static and instance variables, constructors of a current class.
  • If we include “this()” or “super()” inside the constructor, it must be the first statement inside it.
  • this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement).
  • this” can be passed as an argument in the method and constructor calls.

FAQ’s

1. Can we have “this()” and “super()” together?

No, we can not use “this()” and “super()” together.

2. Why “this()” and “super()” keywords cannot be used together?

this()” is used to call the constructor of the current class and “super()” is used to call the constructor of the immediate parent class. If a user wants to call a parent or a current class constructor using the “super()” or “this()” keyword, then it must be the first statement inside the constructor, but both “super()” and “this()” cannot be the first statement simultaneously due to this reason “this()” and “super()” keywords cannot be used together.

3. Why do we use super keyword in Java?

We use the super keyword to refer to the parent class instance, to invoke parent class methods, static and instance variables. The “super()” is used to invoke the immediate parent class constructor.

4. Why super keyword is used first?

Java enforces that the call to super (explicit or not) must be the first statement in the constructor. This is to prevent the subclass part of the object from being initialized before the superclass part of the object being initialized.

Which keyword is used to call parent class constructor and method from within the class?

The super keyword can also be used to access the parent class constructor.

How do you call the parent class constructor inside the child class?

You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.

Which keyword is used to call constructor of parent?

The super keyword can also be used to invoke the parent class constructor.

What Java keyword is used to call the parent constructor from the child constructor?

2) Use of super keyword to invoke constructor of parent class. When we create the object of sub class, the new keyword invokes the constructor of child class, which implicitly invokes the constructor of parent class.