this (keyword)
this is a reference to the current object instance within an instance method or constructor. It is used to disambiguate fields from parameters, pass the current object to another method, or chain constructor calls.
Disambiguating field from parameter
public class Person {
private String name;
public Person(String name) {
this.name = name; // this.name = field; name = parameter
}
}
Constructor chaining
public class Product {
public Product(String name) {
this(name, 0.0); // calls the 2-arg constructor below
}
public Product(String name, double price) { ... }
}
this(...) must be the first statement in the constructor.
Passing "me" to another method
public class Button {
public void render() {
eventBus.register(this); // pass this Button instance
}
}
Returning this for method chaining
public class Builder {
public Builder name(String n) { this.name = n; return this; }
public Builder age(int a) { this.age = a; return this; }
}
new Builder().name("Ada").age(36);
this in static contexts
Static methods do not have a this — they are not associated with any instance. Using this inside a static method is a compile error.