Java this Keyword


In Java, the this keyword is a reference variable that refers to the current object of a class. It helps differentiate between instance variables and parameters when they share the same name, and it can also be used to call methods or constructors within the same class.

In simple words, this tells Java which object you’re currently working with. Whenever you create an object, Java automatically assigns a reference to it, and that reference is accessed using the this keyword.

Why Use this Keyword?

There are several situations where this is important in Java programming:

  1. To refer to the current class variables (especially when local variables shadow them).

  2. To call another constructor from within a constructor.

  3. To call current class methods.

  4. To pass the current object as an argument.

  5. To return the current object from a method.

Let’s explore each of these uses one by one.

Referring to Instance Variables

When method parameters or constructor parameters have the same name as class attributes, this helps distinguish between them.

Example:

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;  // 'this' refers to instance variable
        this.age = age;
    }

    void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Riya", 21);
        s1.display();
    }
}

Output:

Name: Riya, Age: 21

Here, without this, the compiler would not be able to differentiate between the instance variable name and the constructor parameter name.

Calling Another Constructor

You can use this() to call one constructor from another within the same class. This helps avoid code repetition and makes your constructors cleaner.

Example:

class Car {
    String brand;
    int speed;

    Car() {
        this("Unknown", 0); // Calls parameterized constructor
    }

    Car(String brand, int speed) {
        this.brand = brand;
        this.speed = speed;
    }

    void show() {
        System.out.println("Brand: " + brand + ", Speed: " + speed);
    }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car("Honda", 120);
        c1.show();
        c2.show();
    }
}

Output:

Brand: Unknown, Speed: 0  
Brand: Honda, Speed: 120

Note: The call to this() must always be the first statement inside the constructor.

Calling Current Class Methods

You can also use this to call another method from within the same class. This is especially useful when the called method performs a related task that supports the current operation.

Example:

class Message {
    void displayGreeting() {
        System.out.println("Good Morning!");
    }

    void displayFullMessage() {
        this.displayGreeting(); // calling another method using 'this'
        System.out.println("Have a great day!");
    }

    public static void main(String[] args) {
        Message msg = new Message();
        msg.displayFullMessage();
    }
}

Output:

Good Morning!  
Have a great day!

Here, this ensures the method displayGreeting() belongs to the same object that called displayFullMessage().

Passing Current Object as an Argument

Sometimes, you need to pass the current object to another method or constructor. The this keyword makes that possible.

Example:

class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    void show() {
        System.out.println(name + " scored " + marks + " marks.");
    }

    void display() {
        Helper.printStudent(this);  // passing current object
    }
}

class Helper {
    static void printStudent(Student s) {
        s.show();
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Anjali", 92);
        s1.display();
    }
}

Output:

Anjali scored 92 marks.

Here, this is used to pass the reference of the current Student object to another class method.

Returning the Current Object

Sometimes, you might want a method to return the current object itself. This is commonly used in method chaining, where multiple methods are called on the same object in one line.

Example:

class Calculator {
    int value;

    Calculator setValue(int value) {
        this.value = value;
        return this;  // returning current object
    }

    Calculator add(int num) {
        this.value += num;
        return this;
    }

    void show() {
        System.out.println("Result: " + value);
    }

    public static void main(String[] args) {
        Calculator c = new Calculator();
        c.setValue(10).add(20).show();  // method chaining
    }
}

Output:

Result: 30

Here, every method returns the current object, allowing methods to be linked together.

this vs super Keyword

Feature this super
Refers to Current class object Parent class object
Used for Accessing current class members Accessing superclass members
Calls Current class constructor Parent class constructor

Key Rules of this Keyword

  1. this() can only be used inside a constructor.

  2. this() must be the first statement in a constructor.

  3. You can use this anywhere inside an instance method or constructor.

  4. You cannot use this inside static methods because they do not belong to any specific object.

Common Mistake Example

class Test {
    int num;

    void setNum(int num) {
        num = num;  // incorrect - assigns local variable to itself
    }

    void display() {
        System.out.println(num);
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.setNum(5);
        t.display();  // prints 0
    }
}

The output is 0 because the local variable num shadows the instance variable. The correct code uses this.num = num; to assign properly.

Summary of the Tutorial

In this tutorial, you learned about the this keyword in Java — a special reference variable that points to the current object. You saw how it is used to:

  • Differentiate between instance and local variables.

  • Call other constructors within the same class.

  • Invoke methods from the same class.

  • Pass and return the current object.

Understanding this helps write cleaner, less error-prone code and is essential when working with constructors, methods, and object references in Java.


Practice Questions

1. Write a Java program with a class Person that has instance variables name and age. Use the this keyword in a constructor to initialize these variables and display the details using a method.

2. Create a class Book that has two constructors — one default and one parameterized. Use this() in the default constructor to call the parameterized one. Print book details from both constructors.

3. Write a Java program with a class Car that has instance variables brand and price. Use this to differentiate between constructor parameters and instance variables that have the same name.

4. Create a class Calculator where one method add() calls another method displayResult() using this. Demonstrate how this helps call current class methods.

5. Write a program that passes the current object as an argument. Create a class Student with a method display() and another class School with a static method printDetails(Student s). Pass the current Student object to the printDetails() method using this.

6. Create a class Employee with attributes name and salary. Write a method setDetails() that takes parameters and assigns them using this. Print the updated details.

7. Write a Java program that demonstrates method chaining using this. Create a class BankAccount with methods deposit(), withdraw(), and displayBalance(). Each method should return this to allow chaining like account.deposit(1000).withdraw(200).displayBalance();.

8. Create a class Rectangle that has two constructors — one takes only length and calls another constructor using this() that also takes width. Display area for both constructors.

9. Write a class Laptop that uses this to return the current object from a method. Create another method that calls the returned object to print details.

10. Write a program that shows what happens when you forget to use this inside a setter method. Create a class Test with an instance variable num and a method setNum(int num) that mistakenly assigns num = num;. Fix it using this.num = num; and explain the difference.


Try a Short Quiz.

No quizzes available.


Go Back Top