Java Concepts I’m Mastering –> Part 3: The this Keyword
Continuing my journey of mastering Java fundamentals.
Today’s focus: The this keyword —> small word, big importance.
What is this?
this refers to the current object.
It is mainly used when instance variables and constructor parameters have the same name.
Why Do We Need It?
Without this, Java gets confused between:
Instance variables
Constructor or method parameters
Example
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Here:
name (right side) → constructor parameter
this.name → instance variable
Without this, the instance variable wouldn’t be assigned properly.
Other Uses of this
Call another constructor in the same class
Pass current object as a parameter
Return current object
Example (constructor chaining):
class Student {
String name;
int age;
Student(String name) {
this(name, 18);
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
What I Learned
this improves clarity
It avoids ambiguity
It makes constructor design cleaner
Understanding this helped me write more structured OOP code.
Next in the series: Constructor vs Method in Java
Top comments (0)