Within an instance method or a constructor,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 usingthis
.Using
The most common reason for using thethis
with a Fieldthis
keyword is because a field is shadowed by a method or constructor parameter.For example, the
Point
class was written like thisbut it could have been 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; } }Each argument to the second constructor shadows one of the object's fields—inside the constructorpublic 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 thePoint
fieldx
, the constructor must usethis.x
.Using
From within a constructor, you can also use thethis
with a Constructorthis
keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's anotherRectangle
class, with a different implementation from the one in the Objects section.This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.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.