this Keyword
1. What Is this? (beginner)
this = "myself!" — address of current object. Fixes shadowing (param same name as field!) + enables chaining + passes self.
class Student {
String name;
Student(String name) {
// name = name; // USELESS (param = param, field untouched!)
this.name = name; // field = param (correct!)
}
void show() { System.out.println(this.name); } // this optional here
}
4. Traps
thisin static = ERROR (no object!).this(...)must be FIRST line of constructor.this == objcompares self-address (rare).
5. Exam Points
- Shadowing fix program — 5 marks, very frequent.
this()chaining + static ban — 3-5 marks, frequent.