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, 4this(...) 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.0Notes
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
In the tutorial
- Constructors — Constructors in Java: initial field values, the this keyword, several constructors and calling this(...).