What is the purpose of the this
keyword in Java?
Answer:
The most common reason for using the "this" keyword is because a field is shadowed by a method or constructor parameter. 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".