this Keyword in Java with Examples

In this article, we will learn everything about this keyword. In Java, this is a reference variable that refers to the current object.
Check out All 50 Java Keywords with Examples

Let's discuss each of these usages of this keyword with an example.

1. this keyword can be used to refer to a current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:
package com.javaguides.corejava.keywords.thiskeyword;

public class User {
    private int id;
    private String firstName;
    private String lastName;
    private int age;

    public User(int id, String firstName, String lastName, int age) {
        id = id;
        firstName = firstName;
        lastName = lastName;
        age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
    }

    public static void main(String[] args) {
        User user = new User(1, "Ramesh", "Fadatare", 28);
        System.out.println(user.toString());
    }
}
Output:
User [id=0, firstName=null, lastName=null, age=0]
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

The solution of the above problem with this keyword

package com.javaguides.corejava.keywords.thiskeyword;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class UserWithThisKeyword {
    private int id;
    private String firstName;
    private String lastName;
    private int age;

    public UserWithThisKeyword(int id, String firstName, String lastName, int age) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
    }

    public static void main(String[] args) {
        UserWithThisKeyword user = new UserWithThisKeyword(1, "Ramesh", "Fadatare", 28);
        System.out.println(user.toString());
    }
}
Output:
User [id=1, firstName=Ramesh, lastName=Fadatare, age=28]
Note that if local variables(formal arguments) and instance variables are different, there is no need to use this keyword.

2. this keyword can be used to invoke current class method (implicitly)

Below example demonstrates how to invoke the method of the current class by using this keyword.
package com.javaguides.corejava.keywords.thiskeyword;

public class ThisKeywordWithMethod {
    public static void main(String[] args) {
        A a = new A();
        a.print();
    }
}

class A {
    public void display() {
        System.out.println("Inside display method");
    }

    public void print() {
        this.display();
        System.out.println("Inside print method");
    }
}
Output:
Inside display method
Inside print method

3. this() can be used to invoke the current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
To understand how this( ) can be used, let’s work through a short example. First, consider the following class that does not use this( ):
class MyClass {
    int a;
    int b;
    // initialize a and b individually
    MyClass(int i, int j) {
        a = i;
        b = j;
    }
    // initialize a and b to the same value
    MyClass(int i) {
        a = i;
        b = i;
    }
    // give a and b default values of 0
    MyClass() {
        a = 0;
        b = 0;
    }
}
This class contains three constructors, each of which initializes the values of a and b. The first is passed individual values for a and b. The second is passed just one value, which is assigned to both a and b. The third gives a and b default values of zero. By using this( ), it is possible to rewrite MyClass as shown here:
package com.javaguides.corejava.keywords.thiskeyword;

public class ThisKeywordWithConstructor {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        MyClass myClass1 = new MyClass(10);
        MyClass myClass2 = new MyClass(10, 20);

    }
}

class MyClass {
    int a;
    int b;

    // initialize a and b individually
    MyClass(int i, int j) {
        a = i;
        b = j;
    }

    // initialize a and b to the same value
    MyClass(int i) {
        this(i, i); // invokes MyClass(i, i)
    }

    // give a and b default values of 0
    MyClass() {
        this(0); // invokes MyClass(0)
    }
}
Note that call to this() must be the first statement in the constructor.

4. this keyword can be passed as an argument in the method call

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. In below example, we are passing this keyword to printStudent(this) method:
public void print() {
 printStudent(this);
}
Here is a complete program to demonstrate how to use this keyword to pass as an argument in the method call:
package com.javaguides.corejava.keywords.thiskeyword;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ArgumentInMethodThis {
    public static void main(String[] args) {
        Student student = new Student("Ramesh", "STU100", "Physics");
        student.print();
    }
}

class Student {
    private String name;
    private String rollNo;
    private String course;


    public Student(String name, String rollNo, String course) {
        super();
        this.name = name;
        this.rollNo = rollNo;
        this.course = course;
    }

    public void print() {
        printStudent(this);
    }

    private void printStudent(Student student) {
        System.out.println(student.name);
        System.out.println(student.course);
        System.out.println(student.rollNo);
    }
}
Output:
Ramesh
Physics
STU100

5. this keyword can be passed as an argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:
package com.javaguides.corejava.keywords.thiskeyword;

public class ArgumentInConstructorThis {
    public static void main(String[] args) {
        ClassB classB = new ClassB(10, "Demo");
    }
}

class ClassA {

    ClassB classB;
    public ClassA(ClassB classB) {
        this.classB = classB;
        printClassB();
    }
    public void printClassB() {
        System.out.println(this.classB.getId());
        System.out.println(this.classB.getName());
    }
}

class ClassB {
    private int id;
    private String name;

    public ClassB(int id, String name) {
        this.id = id;
        this.name = name;

        new ClassA(this);
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}
Output:
10
Demo

6. this keyword can be used to return the current class instance from the method

We can return this keyword as a statement from the method. In such a case, the return type of the method must be the class type (non-primitive). Let's see the example:
package com.javaguides.corejava.keywords.thiskeyword;

public class ThisReturnExample {
    public static void main(String[] args) {
        DemoClass demoClass = new DemoClass();
        demoClass.test().print();
    }
}

class DemoClass {
    public DemoClass test() {
        return this;
    }

    public void print() {
        System.out.println("Inside Demo Class");
    }
}
Output:
Inside Demo Class
Check out All 50 Java Keywords with Examples

Comments