In Java, the keyword "this" is utilized to indicate the current object within a class and to interact with its properties. Throughout this section, we will explore the application of "this" in relation to variables, functions, and constructors through illustrative instances.
What Is this Keyword in Java?
Within Java programming, the "this" keyword serves as a pointer to the present object within a class. Its primary function involves distinguishing between parameters and instance variables sharing identical names, invoking one constructor from another, and transferring the current object as an input to methods or constructors.
Characteristics of this Keyword
The following are the characteristics of this keyword in Java:
- Represents the Current Object: Think of this as a way for an object to refer to itself. If an object is calling a method, this points to that specific instance.
- Helps Avoid Confusion: If a method parameter has the same name as an instance variable, this makes it clear which one is the instance variable.
- Calls Other Methods in the Same Class: We don't always need this, but we can use it explicitly to call another method within the same class.
- Supports Constructor Chaining: this can be used inside a constructor to call another constructor in the same class, helping reuse code.
- Passes the Current Object as an Argument: Sometimes, we need to send the current object to another method or class. This makes that possible.
- Returns the Current Object: A method can return this, allowing method chaining, which is common in fluent APIs.
1. Using this to Refer to Current Class Instance Variables
In Java, the keyword "this" is employed to indicate the instance variables of the current class. When there is ambiguity between instance variables and parameters, using the "this" keyword helps to clarify and resolve the ambiguity.
Example without this keyword
Let's explore the issue that arises when we omit this keyword through the following example:
Example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
public class Main{
public static void main(String args[]){
Student s1=new Student(111,"Ankit",5000f);
Student s2=new Student(112,"Sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
Explanation:
In the example provided earlier, the parameters (formal arguments) and instance variables are identical. Thus, the 'this' keyword is utilized to differentiate between the local variable and instance variable.
Example: Using this keyword
Let's explore another instance to illustrate how this keyword functions in Java.
Example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
public class Main{
public static void main(String args[]){
Student s1=new Student(111,"Ankit",5000f);
Student s2=new Student(112,"Sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 Ankit 5000.0
112 Sumit 6000.0
Example: Without requiring this keyword
In cases where local variables (formal arguments) and instance variables are distinct, the utilization of the "this" keyword is unnecessary, as demonstrated in the subsequent program:
Example
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class Main {
public static void main(String args[]){
Student s1=new Student(111,"Ankit",5000f);
Student s2=new Student(112,"Sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 Ankit 5000.0
112 Sumit 6000.0
2. Using this to Call Current Class Methods
To access the method of the present class, the this keyword can be utilized. If the this keyword is omitted, it will be automatically inserted by the compiler when invoking the method.
Consider the following example to illustrate the utilization of the this keyword for invoking methods within the current class in Java.
Example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class Main{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m
3. Using this to Call the Current Class Constructor
The this method can be employed to trigger the constructor of the current class, facilitating the reusability of constructors. Essentially, it enables constructor chaining.
Example: Calling Default Constructor From Parameterized Constructor
Consider the following example to illustrate the process of invoking the default constructor from a parameterized constructor in Java.
Example
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
public class Main{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
Example: Calling Parameterized Constructor From Default Constructor
To illustrate calling a parameterized constructor from a default constructor in Java, consider the following example.
Example
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class Main{
public static void main(String args[]){
A a=new A();
}}
Output:
5
hello a
Real usage of this constructor call
Utilize the this constructor invocation to employ the constructor within another constructor, ensuring a continuous chain between constructors, known as constructor chaining. An example illustrating the practical application of the this keyword is presented below.
Utilize the this constructor invocation to recycle the constructor within the constructor. This approach preserves the connection between the constructors, allowing for constructor chaining.
Let's examine the following example that demonstrates the practical application of this keyword.
Example
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course)
{
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee)
{
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
public class Main{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}
Output:
111 ankit java 0.0
112 sumit java 6000.0
Guideline: The invocation of this should appear as the initial statement within the constructor function.
Example
In this instance, a compile-time error is triggered due to the this constructor invocation not being positioned as the initial statement within the constructor.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this.fee=fee;
this(rollno,name,course);//C.T.Error
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class Main{
public static void main(String args[]){
Student s1=new Student(111,"Ankit","Java");
Student s2=new Student(112,"Sumit","Java",6000f);
s1.display();
s2.display();
}}
Output:
Compile Time Error: Call to this must be the first statement in the constructor
4. Using this to Pass the Current Object as a Method Argument
In Java, the "this" keyword is utilized as a parameter in methods, commonly in the context of event handling.
Example
Consider the following example to illustrate the utilization of the this keyword in passing the current object as an argument in a method.
Example
class Main{
void m(Main obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
Main m = new Main();
m.p();
}
}
Output:
method is invoked
Application
In scenarios involving event handling or when there is a need to pass a reference of a class to another, object references are utilized to enable the reuse of a single object across multiple methods.
5. Using this to Pass the Current Object in a Constructor Call
The 'this' keyword can also be passed in the constructor, which can be beneficial when there is a need to utilize a single object across several classes.
Example
Let's consider an example to illustrate the utilization of the keyword 'this' for adding the Current Object in a Constructor Invocation.
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class Main {
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:
6. Using this to Return the Current Class Instance
The return keyword can be utilized to output a statement from a method. When using this approach, it is necessary for the method's return type to match the class type and not be a primitive type.
Syntax
It has the following syntax:
return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
Consider this keyword as an illustration that is being returned as a statement from the function.
Example
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello Java");}
}
class Main{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:
Hello Java
Proving this keyword
Let's demonstrate that this particular keyword points to the instance variable of the current class. Within this code, we are displaying the reference variable, and the values of both variables are identical.
Example
class Main{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
Main obj=new Main();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:
A5@22b3ea59
A5@22b3ea59
Advantages of this Keyword
There are several advantages of this keyword. Some of them are as follows:
- Avoids Confusion: If a method has a parameter with the same name as an instance variable, it helps refer to the instance variable.
- Improves Readability: It makes it clear that you're working with the object's own data.
- Simplifies Constructor Chaining: It allows one constructor to call another, reducing duplicate code.
- Enables Method Chaining: We can call multiple methods in one statement, making the code cleaner.
- Passes the Object Itself: Sometimes, you need to send the current object to another method, and this makes it easy.
Disadvantages of this Keyword
There are several disadvantages of this keyword. Some of them are as follows:
- Risk of Misuse: It can cause bugs if instance and local variables aren't carefully distinguished.
- Coupling Issues: Tightly binds methods/constructors to the instance, reducing modularity.
- Context Limitations: Not usable in static methods, adding complexity.
- Memory Leaks: It may lead to leaks in certain cases like inner classes.
- Multithreading Challenges: Using synchronization can cause performance issues.