Tuesday, May 11, 2021

this Keyword in Java With Examples

this keyword in java is a reference to the current object, meaning the object whose method or constructor is being called. It can be used inside any method or constructor to refer to the current object.

If the definition of this keyword in Java is sounding confusing, let's clear it with an example-

class ThisDemo{
 int age;
 String name;
 ThisDemo(int a, String b){
  age = a;
  name = b;
 }
 void displayData(){
  System.out.println("Age - " + age + " Name- " +name);
  System.out.println("reference of this " + this);
 }
 
}
public class ThisExample {
 public static void main(String[] args) {
  ThisDemo thisDemo = new ThisDemo(10, "Ram");
  thisDemo.displayData();
  System.out.println("reference of ThisDemo " + thisDemo);
 }
}
 

In the given example, it can be seen that in method displayData() this is printed and in the main method thisDemo object is printed. Reference of object thisDemo and reference of this in method dispalyData() would be same as this is reference to the object on which the method is invoked.

Output

 Age - 10 Name- Ram
reference of this org.netjs.examples.ThisDemo@19e0bfd
reference of ThisDemo org.netjs.examples.ThisDemo@19e0bfd

It can be seen in the output that the same reference is printed for object thisDemo and this.

Note that this can't be explicitly assigned a reference to an object of a class it will result in compilation error.

MyClass myObj = new MyClass();
// This line will give error, as assigning reference of an
// object to this is not permitted
this = myObj;

Usage of this keyword in Java

this in Java used in case of instance variable hiding

Before going into how this keyword can be used in case of instance variable hiding first let's see what actually instance variable hiding is. In Java we can't have two local variables with the same name with in the same scope. So it will be compiler error if we try some thing like-

class A {
 int a;
 double b;
 double b;// Compiler error

 public void displayData(){
  System.out.println("Values - a = " + a + " b= " + b);
 }
}

Here we are trying to have two variables with the same name b with in the same scope (scope of the class) which results in compilation error.

But in different scope it is perfectly legal to have variables with the same name, so we can have the variables with the same name in the method as well as in the class as instance variable. Thus it is perfectly legal to have some thing like

class InstanceHiding {
 int a = 50;
 double b = 60;

 public void displayData(){
  int a = 10;
  double b = 20;
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding();
  instanceHiding.displayData();
 }
} 
 

No error here because the variables are with in the different scope. But the point to note here is that local variable hides the instance variable with in the scope of the local variable. As can be seen from the output of the program.

Values a = 10 b = 20.0

With in the method, method variables get priority over the instance variables and hide them. If we comment the variables with in the method then the output would have been -

Values a = 50 b = 60.0

this can be useful in such cases to avoid name collisions, since we know that this in Java refers to the object on which the method is called so this can be used to access the instance variables.
Conventionally people prefer to have same names for variables in the case of constructors to have clarity, use of this helps there to initialize fields.

An Example
class InstanceHiding {
 int a;
 double b;
 InstanceHiding(int a, double b){
  this.a = a;
  this.b = b;
 }
 public void displayData(){  
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding(10, 20);
  instanceHiding.displayData();
 }
}

Here we are referring the instance variables using the this keyword like this.a and initializing them in the constructor.

this keyword used in case of overloaded constructors

In Java this keyword can be used to invoke overloaded constructors in a class. There are 2 restrictions that should be kept in mind while doing that.

  • this() must be the first statement with in the constructor.
  • instance variable of the constructor's class can not be used in a call to this().
class ConstrOverLoading {
 int a;
 double b;
 ConstrOverLoading(int a, double b){
  this.a = a;
  this.b = b;
 }
 ConstrOverLoading(int a){
  this(a, 0.0);
 }
 ConstrOverLoading(){
  this(0);
 }
}

It can be noticed here that only one of the constructor ConstrOverLoading(int a, double b) is doing any assignment other constructors are merely invoking that constructor through this(). This use of this helps in reducing the duplication of code.

Note that while using with in a constructor either this() or super() can be used not both as both have the restriction to be the first statement with in the constructor.

Passing 'this' as an argument in the constructor call/method call

Since this in Java refers to the current object so this can be used as an argument where ever current object is needed.

public class A {
 void anotherMethod(A obj){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  anotherMethod(this);  
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

this keyword used to call methods of a class

Since this in Java refers to the current object so this can also be used to call methods of the class.

public class A {
 void anotherMethod(){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  this.anotherMethod();
  this.toString();
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

That's all for this topic this Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. super Keyword in Java With Examples
  3. Constructor in Java
  4. static Keyword in Java With Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. strictfp in Java
  2. Constructor Chaining in Java
  3. Varargs (Variable-length Arguments) in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. How ArrayList Works Internally in Java
  6. Interface Default Methods in Java
  7. Method Reference in Java
  8. Check if Given String or Number is a Palindrome Java Program

No comments:

Post a Comment