this Keyword in Java

๐Ÿง  What is this?

The this keyword is a reference to the current object in Java. It is used to avoid confusion between class attributes and method parameters when they have the same name.


๐Ÿ”ธ Use Cases:

  1. Distinguish between instance and parameter variables.

  2. Call other constructors in the same class.

  3. Return current object from a method.

  4. Pass current object as an argument.


๐Ÿงช Example:

class Student {
String name;

Student(String name) {
this.name = name; // distinguishes local and global 'name'
}

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


๐Ÿงช Constructor Chaining using this():

class Demo {
Demo() {
this(5);
System.out.println("Default Constructor");
}

Demo(int x) {
System.out.println("Parameterized Constructor: " + x);
}
}


๐Ÿ“Œ Key Points:

  • this refers to the current class object.

  • Helps resolve naming conflicts.

  • Used in method chaining and constructor chaining.

Related Posts