Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
在实例方法或构造函数中,this 是对 当前对象 该方法或构造函数被调用的对象的引用。你可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。
this使用 this 关键字的最常见原因是因为字段被方法或构造函数参数遮蔽 (shadowed)。
例如,Point 类是这样写的
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;
}
}
构造函数的每个参数都会遮蔽 (shadows)对象的某个字段 在构造函数中 x 是构造函数第一个参数的本地副本。要引用 Point 的字段 x,构造函数必须使用 this.x。
this 从构造函数中,还可以使用 this 关键字来调用同一个类中的另一个构造函数。这样做被称为 explicit constructor invocation (显示构造函数调用)。这是另一个 Rectangle 类,它与 Objects 部分中的不同。
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
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;
}
...
}
这个类包含一组构造函数。每个构造函数初始化矩形的一些或全部成员变量。构造函数为初始值没有由参数提供的成员变量提供默认值。例如,无参构造函数在坐标 0,0 处创建 1x1 Rectangle。双参数构造函数调用四参数构造函数,传入宽度和高度,但始终使用 0,0 坐标。和以前一样,编译器根据参数的数量和类型确定调用哪个构造函数。
如果存在对另一个构造函数的调用,则必须是构造函数中的第一行。