this
is
a reference to the current object — the object whose
method or constructor is being called. You can refer to any member
of the current object from within an instance method or a constructor
by using this
.
this
with a Fieldthis
keyword is
because a field is shadowed by a method or
constructor parameter.
For example, the Point
class was written like this
public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } }
public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } }
x
is a local copy of the constructor's
first argument. To refer to the
Point
field x
,
the constructor must use this.x
.
this
with a Constructorthis
keyword
to call another constructor in the same class. Doing so is called an
explicit constructor invocation. Here's another Rectangle
class, with a different implementation from the one in the
Getting Started section
.
public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... }
If present, the invocation of another constructor must be the first line in the constructor.