使用this
关键字
原文: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
在实例方法或构造器中,this
是对当前对象的引用 - 正在调用其方法或构造器的对象。您可以使用this
从实例方法或构造器中引用当前对象的任何成员。
将this
与 Field 一起使用
使用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
与构造器一起使用
在构造器中,您还可以使用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 坐标。和以前一样,编译器根据参数的数量和类型确定要调用的构造器。
如果存在,则另一个构造器的调用必须是构造器中的第一行。