翻译自http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
场景1. 成员变量被某个方法(一般是set方法或者构造函数)中的local变量屏蔽
例如:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
构造函数里的local变量如果也使用x,y呢
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
加上this就指定是本对象的变量而非local变量
场景2. 调用另外一个构造函数
例如:
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;
}
...
}