EMZETT.
Login

this Keyword

In short: A reference to the current object within an instance method or a constructor — mostly used to distinguish a field from a parameter of the same name.

In more detail: Without this, color = color; in a constructor with parameter color would do nothing (the parameter would assign itself to itself). this.color = color; makes it clear: on the left the object field, on the right the parameter. this() (with parentheses) additionally calls another constructor of the same class.

In Depth

class Person {
    private String name;
    private int age;
 
    Person(String name, int age) {
        this.name = name;   // left: field, right: parameter - without "this" it would be ambiguous
        this.age = age;
    }
 
    Person(String name) {
        this(name, 0); // calls the other constructor of the same class
    }
 
    Person growOlder() {
        this.age++;
        return this; // returns the current object - enables method chaining
    }
}
 
Person p = new Person("Anna").growOlder().growOlder();

The most common use of this is to distinguish an object field from a method/constructor parameter of the same name (“shadowing”) — without this.name = name;, the line name = name; would simply assign the parameter to itself, the field would remain unchanged. Two other, rarer uses: this(...) (with parentheses, no dot) calls ANOTHER constructor of the same class within a constructor, to avoid writing initialization code twice (“constructor chaining”, also has to be the first line). And return this; at the end of a method returns the current object, which enables method chaining (“fluent interface”, as in the example above).

In a static method, this isn’t available, since static methods belong to the class itself and can be called with no concrete object — in this context there’s simply no “current object” for this to point to.

See also: Constructors, super Keyword, Objects