Video in progress

What is the this keyword used for?

this is a reference to the current object. You use it to tell a field apart from a parameter with the same name, to call another constructor of the same class with this(...), or to pass the object itself to another method.

📖 Answer

public class Product {
    private final String name;
    private final long price;

    public Product(String name) {
        this(name, 0);                 // delegate to another constructor
    }

    public Product(String name, long price) {
        this.name = name;              // field = parameter
        this.price = price;
    }

    public Product withPrice(long price) {
        return new Product(this.name, price);
    }

    public void register(Catalog catalog) {
        catalog.add(this);             // pass itself
    }
}

One more case is returning return this; in a fluent API to chain calls (common in builders).

Limitations:

  • there is no this inside a static method, because there is no object there;
  • this(...) must be the first line of the constructor.

Be careful: handing this out from inside a constructor (for example, registering it as a listener) is risky, because the object isn't fully built yet, and another thread may see it half-constructed.