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 using this
.
Using this
with a Field
The most common reason for using the this
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; } }
but it could have been written like this:
public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } }
Each argument to the constructor shadows one of the object's fields — inside the constructor x
is a local copy of the constructor's first argument. To refer to the Point
field x
, the constructor must use this.x
.
Lab Design a Point class with 2 variables x and y. Give it the method of move to move to change a point's x and y coordinates, and the mthod of getDistance to calculate the distance between any 2 points. Try to use the "this" keyword in your class design.