this Keyword in Java with Examples

this Keyword in Java

The this keyword in Java is a reference variable that refers to the current object of the class that is currently executing.
In simple words, this represents the current memory address of the object.

✅ Definition

  • this refers to the current object
  • It is used inside constructors, methods, and instance blocks
  • It is explicitly written by the programmer
  • The compiler does not create this implicitly
  • It helps differentiate between instance variables and local variables when they have the same name

🌍 Real-Life Example

Classroom Example
A teacher says: “This student should come forward”
The word “this” refers to the current student being addressed
Similarly, in Java, this refers to the current object.
🔹 Uses of this Keyword in Java

1. Differentiating Instance Variables and Local Variables

When local variables and instance variables have the same name, this is used to avoid confusion.

class Student {
    int id;
    Student(int id) {
        this.id = id;
    }
}
✔ this.id → instance variable
✔ id → local variable

2. Referring to the Current Object

class Test {
    void display() {
        System.out.println(this);
    }
}
Here, this prints the memory reference of the current object.

3. Calling One Constructor from Another (Constructor Chaining)

class Sample {
    Sample() {
        this(10);
        System.out.println("Default Constructor");
    }
    Sample(int x) {
        System.out.println("Parameterized Constructor: " + x);
    }
} 

4. Passing Current Object as a Parameter

class Demo {
    void show(Demo d) {
        System.out.println("Method Called");
    }
    void call() {
        show(this);
    }
}

📌 Important Points to Remember

  • this always refers to the current object
  • It cannot be used in a static context
  • It improves code clarity and readability
  • It is commonly used in constructors

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know