Use of this and super in Java
In this article, I will give you an overview of the keywords this
and super
in Java. Let us start with this keyword.
Uses of this
in Java:
In Java, “this” is a reference variable that always refers to the current object. We can use “this” keyword as follows:
- in the current class to
- can be passed as an argument in a method call
- can be passed as an argument in a constructor call
- to return the current class instance
To refer to the current class instance variable:
If local and instance variables are same i.e. have the same signature, then we can use “this” keyword to distinguish between the local variable and the instance variable. However, if local variables (formal arguments) and instance variables are different, then there is no need to use this keyword.
public class Employee { int id; String name; Employee(int id, String name){ this.id = id; this.name = name; } void display() { System.out.println(id+" "+name); } public static void main(String[] args) { Employee obj1 = new Employee(201, "Amit"); obj1.display(); Employee obj2 = new Employee(301, "Rakesh"); obj2.display(); } }
Output:
To invokes current class constructor:
We can use “this()” constructor to involve the current class constructor. However, this approach is better if there are multiple constructors in the class and you want to reuse them.
Rule: Call to “this ()” must be the first statement inside the constructor.
public class Employee { int id; String name; Employee(){ System.out.println("\ndefault constructor of Employee is invoked!"); } Employee(int id, String name){ this(); //used to invoke current class constructor this.id = id; this.name = name; } void display() { System.out.println(id+" "+name); } public static void main(String[] args) { Employee obj1 = new Employee(201, "Amit"); obj1.display(); Employee obj2 = new Employee(301, "Rakesh"); obj2.display(); } }
Output:
The constructor call is used to reuse the constructor inside another constructor. It helps to maintain the chain between the different constructors. Thus “this()” supports the concept of constructor chaining.
Look at the below example!
public class Employee { int id; String name; String city; Employee(int id, String name){ this.id = id; this.name = name; } Employee(int id, String name, String city){ this(id, name); // now no need to initialize id and name again this.city = city; } void display() { System.out.println(id + " " + name + " " + city); } public static void main(String[] args) { Employee obj1 = new Employee(201, "Amit"); obj1.display(); Employee obj2 = new Employee(301, "Rakesh", "Bhubaneswar"); obj2.display(); } }
Output:
To invokes current class method:
The “this” keyword invokes the current class method implicitly. However, we need not write this.method() while calling a method as the compiler will do it by default.
Look at the below example!
public class Tree { void leaves() { System.out.println("The tree has green leaves!"); } void leavesMiddle() { System.out.println("Middle method invoked"); this.leaves(); //no need to write this.leaves() as compiler does it for you } void leavesFinal() { System.out.println("Final method invoked"); leavesMiddle(); //compiler will by default will add this keyword to invoke leavesMiddle() as this.leavesMiddle() } public static void main(String[] args) { Tree obj = new Tree(); obj.leavesFinal(); } }
Output:
To pass as an argument in the method call:
The “this” keyword can also be passed as an argument in a method. It is mainly used in event handling.
public class Student { void display(Student obj) { System.out.println(" Method display() is invoked"); } void show() { display(this); } public static void main(String[] args) { Student obj = new Student(); obj.show(); } }
Output:
Passed as an argument in the constructor call:
We can also pass the “this” keyword in a constructor. If we want to use one object inside multiple classes, then this constructor call is very useful.
public class Tree { Fruit fob; public Tree(Fruit fob) { this.fob = fob; } void diplay() { System.out.println("Number of Fruits = "+fob.number); // using number member of class Fruit } } public class Fruit { int number = 10; Fruit(){ Tree tob = new Tree(this); tob.diplay(); } public static void main(String[] args) { Fruit obj = new Fruit(); } }
Output:
To return the current class instance:
We can return the “this” keyword as a statement from the method. In such a case, the return type of the method must be the class type which in turn is a non-primitive type. Thus, “this” keyword can act as a return type.
public class Car { Car getModel() { System.out.println("return type of this method is Class type i.e Car\n"); return this; } void display() { System.out.println("Car model is Maruti Suzuki"); } public static void main(String[] args) { Car obj = new Car(); Car obj2 = obj.getModel(); //method returns class type instance obj2.display(); // we can use the above object returned to call another method } }
Output:
We saw that “this” keyword refers to the current class instance variable. In the below program, we are printing the reference variable and “this”. And we can clearly see that outputs of both the variables are same.
public class Car { void getModel() { System.out.println(this); } public static void main(String[] args) { Car obj = new Car(); System.out.println(obj); obj.getModel(); } }
Output:
Uses of super in Java:
Super always refers to the object of the superclass or base class. There are three uses of super:
- Super refers to the immediate parent class instance variable.
- Invokes immediate parent class constructor.
- Invokes immediate parent class method.
Super refers to immediate parent class instance variable:
public class Vehicle { int speed = 50; } public class Bike extends Vehicle { int speed = 100; void display() { System.out.println("Speed of current class Bike is = "+ speed); System.out.println("Speed of parent class Vehicle is = "+super.speed); } public static void main(String[] args) { Bike obj = new Bike(); obj.display(); } }
Output:
Invokes immediate parent class constructor
public class Vehicle { public Vehicle() { System.out.println("Vehicle is cretaed!"); } } public class Bike extends Vehicle { public Bike() { super(); System.out.println("Bike is created"); } public static void main(String[] args) { Bike obj = new Bike(); } }
Output:
Whenever we want to call “parameterized” constructor of the parent class from the constructor of a subclass, “super()” is mandatory. And “super()” must be the first statement inside that constructor.
public class Sports { int players; public Sports(int players) { System.out.println("Parameterized constructor of class Sports"); this.players = players; System.out.println("Value of players = "+ players); } } public class FootBall extends Sports { int players_in_football; public FootBall() { super(10); System.out.println("\nDefault constructor of FootBall"); this.players_in_football = 11; System.out.println("Value of players_in_football = "+ players_in_football); } public static void main(String[] args) { FootBall obj = new FootBall(); } }
Output:
Look at the below diagram. It lists all the cases of when super() is mandatory and when it is optional.
Invokes immediate parent class method
The keyword “super” invokes the parent class method. It should be used when both subclass, as well as the parent class, contains the same method. The “super” keyword is used to distinguish between the parent class instance variable and current class instance variable.
public class Subject { void message() { System.out.println("Subject is Mathematics"); } } public class Chapter extends Subject { void message() { System.out.println("Chapter is Probability!"); } void display() { super.message(); //invokes paarent class message() method message(); //invokes current class message() method } public static void main(String[] args) { Chapter obj = new Chapter(); obj.display(); } }
Output: