Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

this

A reference to the current object — the one whose method or constructor is running.

Available since: Java 1.0

Syntax

this.field; this(arguments);

Examples

Telling a field apart from a parameter with the same name:

class Point {
    int x;
    int y;
 
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
 
void main() {
    var p = new Point(3, 4);
    IO.println(p.x + ", " + p.y);
}

Output:

3, 4

this(...) calls another constructor of the same class:

class Account {
    String owner;
    double balance;
 
    Account(String owner) {
        this(owner, 0);
    }
 
    Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }
}
 
void main() {
    var a = new Account("Oleg");
    IO.println(a.owner + ": " + a.balance);
}

Output:

Oleg: 0.0

Notes

Without this, x = x would assign the parameter to itself and the field would stay zero. A this(...) call must be the first statement of a constructor. Static methods have no this.

See also

  • super — Refers to the parent class: calls its constructor or its version of a method.
  • new — Creates a new object or array and calls the constructor.
  • static — Makes a field or method belong to the class itself rather than to each object.

In the tutorial

  • Constructors — Constructors in Java: initial field values, the this keyword, several constructors and calling this(...).

Thanks for reading!

Donate to the site — we work hard for you.