JOOPs Through Java
All lessons

Unit 3 · Classes and Objects · 7 min

The this keyword

`this` refers to the current object. It is mostly used when a parameter has the same name as a field.

Why this matters

Every real-world Java class uses this in constructors and setters, so you will see it constantly.

Real-life analogy

In a classroom, if two students are called Arjun, the teacher says 'this Arjun' while pointing. `this` is that pointing finger.

Example

Java
class Student {
    String name;
    int rollNumber;

    Student(String name, int rollNumber) {
        this.name = name;              // field = parameter
        this.rollNumber = rollNumber;
    }

    void display() {
        System.out.println(this.rollNumber + " - " + this.name);
    }
}

public class Main {
    public static void main(String[] args) {
        new Student("Ananya Rao", 12).display();
    }
}

Output

12 - Ananya Rao

Step by step

  1. 1The parameter `name` hides the field `name` inside the constructor.
  2. 2`this.name` clearly means the field of the current object.
  3. 3`name` alone means the parameter.
  4. 4Without `this`, the line `name = name;` would just assign the parameter to itself and the field would stay null.

Key points

  • this = reference to the current object
  • Solves the field/parameter name clash
  • this() can call another constructor of the same class
  • Cannot be used inside static methods

Common mistakes

  • Writing `name = name;` and wondering why the field is null
  • Using this inside main or any static method

Try it yourself

  • Rewrite your Book constructor using parameters with the same names as the fields plus this.
  • Add a setName(String name) method that uses this.
Open the practice notebook