this Keyword
The this keyword in Java is a reference variable that refers to the current object of a class. It is primarily used to resolve ambiguity, improve code clarity, and support constructor chaining. This is a high-frequency interview topic and essential for clean object-oriented design.
What Is this?
- Refers to the current object
- Used inside instance methods and constructors
- Cannot be used in a static context
- Enhances readability and correctness
Basic Syntax
this.variableName
Why this Keyword Is Needed
Problem Without this
class Student {
int age;
Student(int age) {
age = age; // ambiguous
}
}
❌ Instance variable is not updated.
Solution Using this
class Student {
int age;
Student(int age) {
this.age = age;
}
}
✔ Correctly assigns value to instance variable.
Uses of this Keyword (Very Important)
1. Refers to Instance Variables
Resolves name conflict between parameters and instance variables.
this.age = age;
2. Invokes Current Class Method
void display() {
System.out.println("Display");
}
void show() {
this.display();
}
✔ this is optional here, but improves clarity.
3. Constructor Chaining Using this()
Calls another constructor of the same class.
class Test {
Test() {
this(10);
System.out.println("No-arg");
}
Test(int a) {
System.out.println("Parameterized: " + a);
}
}
Rules:
- this() must be the first statement
- Only one this() allowed per constructor
4. Passing Current Object as Argument
void show(Student s) {
System.out.println(s.age);
}
void call() {
show(this);
}
✔ Useful for callback or chaining scenarios.
5. Returning Current Object
Student getObject() {
return this;
}
✔ Supports method chaining.
Where this Cannot Be Used
❌ Static Context
static void test() {
// this.x = 10; // Compile-time error
}
Reason: Static methods belong to the class, not objects.
this vs super
| Feature | this | super |
|---|---|---|
| Refers to | Current class object | Parent class object |
| Accesses | Current class members | Parent class members |
| Constructor call | this() | super() |
| Static context | ❌ Not allowed | ❌ Not allowed |
Common Beginner Mistakes
- Forgetting this in constructors
- Using this in static methods
- Placing this() not as first statement
- Confusing this with super
Interview-Ready Answers
Short Answer
The this keyword refers to the current object of a class.
Detailed Answer
In Java, the this keyword is a reference to the current object. It is used to resolve ambiguity between instance variables and parameters, call current class constructors or methods, pass the current object as an argument, and support method chaining.
Key Takeaway
The this keyword provides clarity, correctness, and control in object-oriented programming. Proper use of this leads to cleaner and more maintainable Java code.