An Introduction to “this” Keyword in Java
The article below explains the usage of this keyword in java with suitable examples and descriptions.
The “this” keyword in Java has various uses. It acts as a reference variable in Java that represents the current object. It is primarily used to differentiate between local variables and instance variables in an object. With the help of examples, this blog will help you understand Java this keyword and how to use it.
Table of Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
What is ‘this’ keyword in Java?
This keyword in Java refers to the ‘current object’ in a method or constructor. It is used to reduce the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Also, Read Inheritance in Java.
Using “this” keyword for different purposes
Following are the uses of Java this keyword.
Also, Read Data Types in Java – Primitive and Non-Primitive Data Types Explained
“this” with an instance variable
Usually, the local variables in a constructor or a method can hide (shadow) the instance variables. In such cases, we use Java this keyword to distinguish between them. Here, this keyword is used with a variable means that the variable is an instance variable and belongs to the current object ie, the object responsible for calling the constructor or the method.
Example:
class Rectangle { double length; double breadth; Rectangle(double length, double breadth) { this.length = length; //using this to point out above variables this.breadth = breadth; } double calculateArea() { return length*breadth; }}class this_keyword{ public static void main(String[] args) { Rectangle myrec = new Rectangle(3,4); System.out.println("Area of Rectangle: " +(myrec.calculateArea())); }}
Output:
Area of Rectangle: 12.0
Also, Read: Java Operators Explained
Using “this” inside a constructor to call another constructor
“this” keyword can also be used to call the current class constructor from within a constructor.
Read: Constructors in Java
Example:
class Rectangle { double length; double breadth; Rectangle() { System.out.println("Non-argument constructor called!"); } Rectangle(double length, double breadth) { this(); //gives call to current class constructor this.length = length; //using this to point out above variables this.breadth = breadth; } double calculateArea() { return length*breadth; }}class this_keyword{ public static void main(String[] args) { Rectangle myrec = new Rectangle(3,4); System.out.println("Area of Rectangle: " +(myrec.calculateArea())); }}
Explanation:
The call to this() inside the parameterized constructor gives a call to the current class (Rectangle) no-argument constructor, printing the statement “No-argument constructor called!” on the console.
Note: The call to this keyword should be the first statement inside the constructor; else it yields a compile-time error. It is mainly used for the purpose of code reusability.
Output:
Non-argument constructor called! Area of Rectangle: 12.0
Read: Implementing Array in Java
This to call the current class method
This keyword is also used to call a method of the current class.
Example:
class Rectangle { double length; double breadth; Rectangle(double length, double breadth) { this.length = length; //using this to point out above variables this.breadth = breadth; } void calculateArea() { double area = length*breadth; System.out.println("Area of the Rectangle: " +area); } void callmethod() { this.calculateArea(); //calls current class method }}class this_keyword{ public static void main(String[] args) { Rectangle myrec = new Rectangle(3,4); myrec.calculateArea(); Rectangle myrec2 = new Rectangle(7,4); myrec2.callmethod(); }}
Explanation:
The call to the method calculateArea() by callmethod() is actually interpreted by the compiler as this.calculateArea(). As, this refers to the current object, here it means myrec.calculateArea() for the first time and myrec2.calculateArea() for the second time.
Output:
Area of the Rectangle: 12.0 Area of the Rectangle: 28.0
Also, Read: Method Overriding in Java
Passing this to a method
“this” keyword can also be passed as an argument to a method that again refers to the current object.
Example:
class Rectangle { double length; double breadth; Rectangle(double l, double b) { length = l; breadth = b; } void calculateArea(Rectangle obj) { System.out.println("Area of the Rectangle: " +obj.length*obj.breadth); } void callmethod() { calculateArea(this); }}class this_keyword{ public static void main(String[] args) { Rectangle myrec = new Rectangle(3,4); myrec.callmethod(); Rectangle myrec2 = new Rectangle(7,4); myrec2.callmethod(); }}
Explanation:
The program above, gives a call to a method callmethod() using two objects myrec and myrec2. The callmethod(), in turn, gives a call to calculateArea() method which passes this as an argument. This here refers to the current object myrec and therefore is mapped to the reference obj of class Rectangle. That’s why, obj.length and obj.breadth is calculating the area for the first rectangle as 12.0 and 28.0 for the second rectangle.
Output:
Area of the Rectangle: 12.0 Area of the Rectangle: 28.0
Also read: Super Keyword in Java
Passing this to a constructor
Here, this can be used to pass as an argument to a constructor.
Example:
class Rectangle { double length; double breadth; Rectangle() { Rectangle r = new Rectangle(this); } Rectangle(Rectangle rt) { rt.length = 10; //using this to point out above variables rt.breadth = 12; } double calculateArea() { return length*breadth; }}class this_keyword{ public static void main(String[] args) { double area; Rectangle myrec = new Rectangle(); System.out.println("Area of Rectangle: " +(myrec.calculateArea())); }}
Explanation:
The creation of myrec object invokes the no-argument constructor of the class Rectangle. The no-argument constructor further creates an object r of Rectangle and is passed as a parameter (referring to myrec here) which gives a call to the parameterized constructor of the class Rectangle on myrec. Then, myrec is then mapped to the reference o, initializing the instance variables length and breadth as 10 and 12, respectively. Hence, printing 120.0.
Output:
Area of Rectangle: 120.0
Also, Read Final Keyword in Java
Using this as the return type of a method
A method can also return objects from itself to the calling method. In such a case, the method’s return type is the class name. Using this as the method’s return type means returning the class’s current instance.
Example:
class Rectangle { double length; double breadth; Rectangle(double l, double b) { length = l; breadth = b; } Rectangle meth() { Rectangle r = new Rectangle(length*10, breadth*10); return this; }}class this_keyword{ public static void main(String[] args) { Rectangle myrec = new Rectangle(3,4); Rectangle ob; System.out.println("The original length and breadth: "+myrec.length +" and " +myrec.breadth); ob = myrec.meth(); System.out.println("The modified length and breadth: "+ob.length +" and " +ob.breadth); }}
Explanation:
In the above example, the meth() method returns this to its calling method main. Here, this refers to the current instance of Rectangle i.e., myrec not r. Therefore, the original and the modified length and breadth are the same.
Output:
The original length and breadth: 3.0 and 4.0 The modified length and breadth: 3.0 and 4.0
Also Read: Top Java Interview Questions
Conclusion
Hope the above blog helped you to understand this keyword in Java better. We have also used examples to provide you with more clarity about Java “this” keyword.
For more, Read: 8 Most Important Data Structures a Programmer Must Know
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio
Comments
(1)
L
9 months ago
Report Abuse
Reply to Laxmikanth