This Keyword in Java


What is this?

In Java, this is a reference variable that refers to the current object (the object that is calling the method or constructor).

Why use this?

We use this keyword to:

  1. Differentiate between class fields and parameters with the same name
  2. Call other constructors in the same class
  3. Pass the current object as a parameter
  4. Return the current object
  5. Call current class methods
Example 1: Differentiating instance variables from parameters
    
    class Student {
        String name;

        // Constructor with parameter
        Student(String name) {
            this.name = name;  // 'this.name' is the class variable, 'name' is the parameter
        }

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

    public class Main {
        public static void main(String[] args) {
            Student s = new Student("Alice");
            s.display();
        }
    }
    
    
Output:
    
    Name: Alice
    
    
Example 2: Calling another constructor
    
    class Box {
        int length, width;

        // Default constructor
        Box() {
            this(10, 20);  // Calls the parameterized constructor
        }

        // Parameterized constructor
        Box(int length, int width) {
            this.length = length;
            this.width = width;
        }

        void display() {
            System.out.println(length + " x " + width);
        }
    }

    public class Main {
        public static void main(String[] args) {
            Box b = new Box();
            b.display();
        }
    }
    
    
Output:
    
    10 x 20
    
    
Example 3: Passing current object
    
    class A {
        void display(A obj) {
            System.out.println("Passed object: " + obj);
        }

        void show() {
            display(this);  // passing current object
        }
    }
    
    
Summary: this keyword is used for:
Use Case Example
Access current object's field this.name
Call another constructor this(...)
Pass current object someMethod(this)
Return current object return this;