Home » Java Tutorial » Java this Keyword

Java this Keyword



Java

We use Java this keyword to refer to the current instance or variable in a method or a constructor. We can also call it as a reference variable. In this tutorial, we will understand how to use the java this keyword in various contexts.

Usage of Java this keyword

The main objective of using java this keyword is to differentiate between the instance variable and local variable. Below are other different usages:

  • To refer to the current class instance variable
  • Invoke current class method implicitly
  • To invoke the current class constructor
  • Pass as an argument in the method call
  • Pass as an argument in the constructor call
  • Return current class instance from method

Using Java this keyword as a class instance variable

First, let’s see what happens when both the instance variable and parameter have the same name. In the below example, we have instance variable and parameters having the same name that is rollno and name. Now when it calls the method setDetails the compiler gets confused as to which is instance variable and which is a parameter. Since we have not initialized any value for the instance variables, while calling the method displayDetails it displays null or value.

public class Student {
  
  public int rollno;
  public String name;
  
  public void setDetails(String name, int rollno) {
    name = name;
    rollno = rollno;
  }
  
  public void displayDetails() {
    System.out.println("Name: " + name);
    System.out.println("RollNo: " + rollno);
  }

  public static void main(String[] args) {
    Student s = new Student();
    s.setDetails("Rakesh", 111);
    s.displayDetails();
  }

}
Name: null
RollNo: 0

Now suppose, we are using the java this keyword to refer to instance variable as in the below example. Now the compiler will understand that this.name and this.rollno refers to the instance variable that we have declared initially and assigns the parameter values of name and rollno accordingly. Internally, when it calls the setDetails method, it replaces the java this keyword with the object name s as below.

Java this keyword

Below is the code to illustrate the usage of the java this keyword as an instance variable.

public class Student {
  
  public int rollno;
  public String name;
  
  public void setDetails(String name, int rollno) {
    this.name = name;
    this.rollno = rollno;
  }
  
  public void displayDetails() {
    System.out.println("Name: " + name);
    System.out.println("RollNo: " + rollno);
  }

  public static void main(String[] args) {
    Student s = new Student();
    s.setDetails("Rakesh", 111);
    s.displayDetails();
  }

}
Name: Rakesh
RollNo: 111

In case, we are using different names for instance variable and parameter, then we don’t need to use the java this keyword. When it executes the statement, the compiler internally appends the java this keyword to the variable and then replaces it with the current object name. Below is an example where we have 2 objects and using different names for instance variable and parameter.

READ  Do-While Loop in Java

Java this keyword

When it calls the method using s1 object, it replaces the this keyword with the object name and hence becomes s1.studentname and s1.studentrollno. Similarly, when it calls the method using s2 object, it replaces internally as s2.studentname and s2.studentrollno.

public class Student {
  
  public int studentrollno;
  public String studentname;
  
  public void setDetails(String name, int rollno) {
    studentname = name;
    studentrollno = rollno;
  }
  
  public void displayDetails() {
    System.out.println("Name: " + studentname);
    System.out.println("RollNo: " + studentrollno);
  }

  public static void main(String[] args) {
    Student s1 = new Student();
    Student s2 = new Student();
    s1.setDetails("Rakesh", 111);
    s1.displayDetails();
    s2.setDetails("Kiran", 100);
    s2.displayDetails();
  }

}

Name: Rakesh
RollNo: 111
Name: Kiran
RollNo: 100

We can also use the java this keyword in getter and setter methods to set and return the instance variables which is mainly used in Inheritance. Below is an example of getter and setter methods where we have used the java this keyword.

class Vehicle {
  private String name;
  
  public void setName(String name) {
    this.name = name;
  }
  
  public String getName() {
    return name;
  }
}

public class Car extends Vehicle{

  public static void main(String[] args) {
    Car c = new Car();
    c.setName("BMW");
    System.out.println("Vehicle name: " + c.getName());
  }

}

Vehicle name: BMW

Using Java this keyword to call the method

We can use the java this keyword to call a method in a class. Though it is not mandatory, even if we do not mention, the compiler internally calls the method using the this keyword.

Java this keyword

In the below example, we have used the java this keyword to call the method displayAccount. Even if we don’t use it, the compiler internally adds this keyword to it while calling the method as seen in the above pictorial representation.

public class Account {

  public int accno;
  
  public void setAccountno(int accountnumber) {
    accno = accountnumber;
    this.displayAccountno(); //same as displayAccountno()
  }
  
  public void displayAccountno() {
    System.out.println("Account number: " + accno);
  }
  public static void main(String[] args) {
    Account a = new Account();
    a.setAccountno(123456);

  }

}
Account number: 123456

Using Java this keyword to call a constructor

We can use this keyword to call any constructor within the class. We use it mainly for constructor chaining which is calling a constructor within a constructor that helps in code reusability Based on the constructor type, we can pass the parameters. Calling a constructor using the java this keyword should always be the first statement, else it will throw compilation error.

READ  If else in Java

Another important point to note is that we cannot use this() and super() together. It allows us to use only either of them in a constructor.

Different ways of calling constructors:

this() – default constructor

this(parameter) – parameterized constructor

Below is an example of calling a constructor with a parameter using this keyword. Inside the first constructor, we call another constructor with a single parameter. We are also calling another method from the constructor using this keyword.

public class Employee {

  public String empname;
  public int empno;
  public String role;
  
  Employee(String name, int empno){
    this("Manager");
    this.empname = name;
    this.empno = empno;
    this.showDetails(empname, empno, role);
  }
  
  Employee(String role) {
    this.role = role;
  }
  
  public void showDetails(String empname, int empno, String role) {
    System.out.println(empname + " " + empno + " " + role);
  }
  
  public static void main(String[] args) {
    Employee e = new Employee("Ravi",4235643);
  }

}
Ravi 4235643 Manager

We can also call a constructor without any parameter using this keyword as in the below example.

public class Employee {

  public String empname;
  public int empno;

  
  Employee(String name, int empno){
    this();
    this.empname = name;
    this.empno = empno;
    this.showDetails(empname, empno);
  }
  
  Employee() {
    System.out.println("Calling constructor without parameter");
  }
  public void showDetails(String empname, int empno) {
    System.out.println(empname + " " + empno);
  }
  
  public static void main(String[] args) {
    Employee e = new Employee("Tejas",12345);
  }

}
Calling constructor without parameter
Tejas 12345

Suppose we try to call multiple constructors of different types using the java this keyword from the same constructor, it will result in a compilation error.

public class Employee {

  public String empname;
  public int empno;
  public String role;
  
  Employee(String name, int empno){
    this();
    this("Manager");
    this.empname = name;
    this.empno = empno;
    this.showDetails(empname, empno, role);
  }
  
  Employee(String role) {
    this.role = role;
  }
  
  Employee() {
    System.out.println("Calling constructor without parameter");
  }
  public void showDetails(String empname, int empno, String role) {
    System.out.println(empname + " " + empno + " " + role);
  }
  
  public static void main(String[] args) {
    Employee e = new Employee("Ravi",4235643);
  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  Constructor call must be the first statement in a constructor

  at Employee.<init>(Employee.java:9)
  at Employee.main(Employee.java:27)

Using Java this keyword as an argument in the method call

We can use the java this keyword as an argument while calling a method. This is mainly used for event handling.

In the below example, we are using this keyword as a parameter to call the display method. Instead of the current class object which is the argument of the display method, we are using this keyword as the argument. During execution, it internally replaces this keyword with the object name.

public class ClassA {
  public void display(ClassA obj) {
    System.out.println("Display method");
  }
  public void show() {
    System.out.println("Show method");
    display(this);
  }
  
  public static void main(String[] args) {
    ClassA a = new ClassA();
    a.show();

  }

}
Show method
Display method

Using this keyword as an argument in the constructor call

We can use this keyword as an argument in the constructor call when we want to use the same object in multiple classes.

READ  Java Access Modifier

For example, in the below code, we have 2 classes ClassX and ClassY. Within the default constructor of ClassX, we are creating an object instance for ClassY where we pass this keyword as an argument. This is because, in the ClassY constructor, we have a ClassX object as the parameter. So in this way, we can reuse the ClassX object in ClassY. Using this object, we can access the value of x which is in ClassX from the method showData which is in ClassY.

class ClassY {
  ClassX obj;
  ClassY(ClassX obj){
    this.obj = obj;
  }
  
  public void showData() {
    System.out.println("Value of x: " + obj.x);
  }
}
public class ClassX {
  int x = 20;
  
  ClassX(){
    ClassY objy = new ClassY(this);
    objy.showData();
  }

  public static void main(String[] args) {
    
    ClassX objx = new ClassX();
  }

}
Value of x: 20

Using this keyword to return the current class instance

We can also use the java this keyword to return a class instance. When using this keyword for such a purpose, we should always use the class type as a return type for that method.

Let’s understand this with an example below. In the method getValue, we are returning the class instance using the java this keyword. Hence the return type of the method is TestDemo which will return the class object. Using this object we can call the displayValue method.

public class TestDemo {

  String value;
  
  TestDemo() {
    value = "Java tutorial";
  }
  
  public TestDemo getValue() {
    return this;
  }
  
  public void displayValue() {
    System.out.println("String value: " + value);
  }
  public static void main(String[] args) {
    TestDemo t = new TestDemo();
    t.getValue().displayValue();
  }

}
String value: Java tutorial

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!! You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Abhishek

Abhishek was able to crack Microsoft after practicing questions from TutorialCup