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
A teacher says: “This student should come forward”
🔹 Uses of this Keyword in JavaWhen 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
void display() {
System.out.println(this);
}
}
Sample() {
this(10);
System.out.println("Default Constructor");
}
Sample(int x) {
System.out.println("Parameterized Constructor: " + x);
} class Demo {
void show(Demo d) {
System.out.println("Method Called");
}
void call() {
show(this);
}
The word “this” refers to the current student being addressed
Similarly, in Java, this refers to the current object.
1. Differentiating Instance Variables and Local Variables
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
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
Post a Comment