使用此关键字
在实例方法或构造函数中,this
是对当前对象的引用,该对象是正在调用其方法或构造函数的对象。您可以使用this
从实例方法或构造函数中引用当前对象的任何成员。
与字段一起使用
使用this
关键字的最常见原因是因为字段被方法或构造函数参数所遮盖。
例如,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;
}
}
构造函数的每个参数都遮蔽了对象的一个字段-构造函数 x
内部是构造函数第一个参数的本地副本。要引用Point
字段 x
,构造函数必须使用this.x
。
与构造函数一起使用
在构造函数中,您还可以使用this
关键字来调用同一类中的另一个构造函数。这样做称为显式构造函数调用。这是另一个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 坐标。和以前一样,编译器根据参数的数量和类型确定要调用的构造函数。
如果存在,则另一个构造函数的调用必须是该构造函数的第一行。