The this keyword
The this keyword refers to the current object instance. It is used to:
- Distinguish instance variables from parameters with the same name.
- Call another constructor from a constructor (
this(...)). - Pass the current object as an argument.
- Return the current object from a method.
1. Resolve name conflicts:
class Person { String name; Person(String name) { this.name = name; // this.name refers to instance variable }}2. Call another constructor:
class Rectangle { int width, height; Rectangle() { this(0, 0); // calls parameterized constructor } Rectangle(int w, int h) { width = w; height = h; }}3. Pass current object:
class Processor { void process(Person p) { ... }}
class Person { void submit() { Processor proc = new Processor(); proc.process(this); // pass current Person object }}4. Return current object (method chaining):
class Counter { int count; Counter increment() { count++; return this; }}Counter c = new Counter().increment().increment(); // chaining