EMZETT.
Login

this Keyword

In short: A reference to the current object itself — used within a method or a constructor to explicitly access your own fields instead of local variables with the same name.

In more detail: this matters especially when a parameter has the same name as a field of the class (e.g. this.name = name;) — without the keyword, it wouldn’t be clear whether the field or the parameter is meant. In some languages, this (or an equivalent like self) is also used to call another constructor of the same class.

In Depth

class Person {
    String name;
 
    Person(String name) {
        this.name = name;   // this.name = the field, name = the parameter
    }
}

Without this, name = name; in the constructor would be pointless — both sides would refer to the PARAMETER (the closer name “wins” in most languages, a principle called “shadowing”), and the class’s field would remain unchanged. this.name, by contrast, makes it unambiguous: “the field of THIS object”, not the parameter.

Beyond simple naming-conflict resolution, this is used for several other purposes:

  • Constructor chaining: this(...) (instead of super(...)) calls ANOTHER constructor of the same class, to avoid writing initialization code twice.
  • Passing yourself as a parameter: a method can pass this to another function, to give it access to the current object (e.g. for certain event-listener or observer patterns).
  • Method chaining: if a method returns this itself (return this;), several method calls on the same object can be chained together (object.setA(1).setB(2).setC(3)), which enables a smoothly readable, “fluent” programming style.

An important conceptual point: this only exists within NON-static methods and constructors, because it refers to a specific object — static methods belong to the class itself, not to an individual instance, and therefore have no “current object” for this to refer to.

See also: Objects, Constructors, super Keyword