May 14, 2022

this in Java With Examples

this keyword in Java is the reference to the current object. To make it clearer, when you invoke any method (or constructor at the time of object creation), using an object of the class then this keyword is the reference to the object used to call the method.

For example-

public class MainClass implements MyInterface{	
  public static void main(String[] args) {
    MainClass obj = new MainClass();
    MainClass obj1 =  obj.showMessage("Hello");
    if(obj == obj1) {
      System.out.println("Both objects have the same reference");
    }
  }

  public MainClass showMessage(String msg) {		
    System.out.println("" + msg);
    return this;
  }
}
Output
Hello
Both objects have the same reference

In the example using the class object a method is called and from that method 'this' is returned. Since 'this' is a reference to the current object that is why on comparing the object references those are equal.

How to use this keyword in Java

this keyword in Java can be used in many scenarios.

  1. To resolve name space collision between instance and local variable. See example.
  2. To call one constructor from another in case of constructor overloading. See example.
  3. To call any method. See example.
  4. To pass as an argument when object has to be passed. See example.

Using this to access instance variables

Generally in case of constructors it is a common practice to give the local variables with in the constructor same name as the instance variables. In that case local variables hide the instance variables and local variables take precedence over instance variables with in the context of that constructor. Since this is a reference to the object itself so this keyword can be used to access instance variables in such scenario.

public class ConstructorDemo {
  int num;
  String name;
  // Parameterized constructor
  private ConstructorDemo(int num, String name){
    this.num = num;
    this.name = name;
  }
	
  // no-arg constructor
  private ConstructorDemo(){
    
  }

  public static void main(String[] args) {
    ConstructorDemo cd = new ConstructorDemo(10, "knpCode");
  }
}

As you can see in the example code, constructor has the local variables with the same name as the instance variables and this keyword is used to resolve the conflict.

Using this to call overloaded constructors

You can use this to call one constructor from another in case of overloaded constructor so that only one of the constructor actually do the initialization.

public class ConstrChaining {
  int a;
  double b;
  String name;
  ConstrChaining(){
    this(0);
  }
  ConstrChaining(int a){
    this(a, 0.0);
  }
  ConstrChaining(int a, double b){
    this(a, b, null);
  }
  ConstrChaining(int a, double b, String name){
    this.a = a;
    this.b = b;
    this.name = name;
  }
  public static void main(String[] args) {
    ConstrChaining cc = new ConstrChaining();
    System.out.println("a- " + cc.a + " b- " + cc.b + " name- " + cc.name);
    
    ConstrChaining cc1 = new ConstrChaining(5, 7.8);
    System.out.println("a- " + cc1.a + " b- " + cc1.b + " name- " + cc1.name);
    
    ConstrChaining cc2 = new ConstrChaining(18, 13.45, "knpCode");
    System.out.println("a- " + cc2.a + " b- " + cc2.b + " name- " + cc2.name);
  }
}

In the example you can see that the initialization is ultimately done by the following constructor-

  ConstrChaining(int a, double b, String name){
    this.a = a;
    this.b = b;
    this.name = name;
  }

All the other constructors are using this keyword to form a chain to call the constructor where initialization is finally done.

Using this keyword to call any method

Since this is the reference to the current object so this can also be used to call the methods of the class.

public class MainClass implements MyInterface{
  public static void main(String[] args) {
    MainClass obj = new MainClass();
    obj.showMessage("Hello");
  }
	
  public void showMessage(String msg) {		
    System.out.println("Message- " + msg);
    // calling method using this
    this.callThis();
  }
	
  public void callThis() {
    System.out.println("Method called using this..");
  }	
}
Output
Message- Hello
Method called using this..

this can be passed as an argument when object has to be passed

Since this is the reference to the current object so you can pass this as an argument where object needs to be passed.

public class MainClass implements MyInterface{
  public static void main(String[] args) {
    MainClass obj = new MainClass();
    obj.showMessage("Hello");	
  }
	
  public void showMessage(String msg) {		
    System.out.println("Message- " + msg);
    // passing this as an argument
    callThis(this);
  }
	
  public void callThis(MainClass obj) {
    System.out.println("this passed as an argument..");
  }	
}

That's all for the topic this in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment