在实例方法或构造器中,this是对当前对象的引用,该对象是正在调用其方法或构造器的对象。您可以使用this,从实例方法或构造器中引用当前对象的任何成员。

字段中使用this

使用this关键字的最常见原因是因为字段被方法或构造器参数遮蔽(shadow)
例如,Point该类是这样写的
public class Point {
public int x = 0;
public int y = 0;

  1. ** //constructor**<br />** public Point(int a, int b) {**<br />** x = a;**<br />** y = b;**<br />** }**<br />}<br />但它也可能是这样写的:<br />public class Point {<br /> public int x = 0;<br /> public int y = 0;
  2. ** //constructor**<br />** public Point(int x, int y) {**<br />** this.x = x;**<br />** this.y = y;**<br />** }**<br />}<br />构造器的每个参数都遮蔽了对象的字段-构造器内部的**`x`**是构造器第一个参数的局部副本。要引用`Point`字段**`x`**,构造器必须使用`this.x`。

构造器中使用this

在构造器中,您还可以使用this关键字来调用同一类中的另一个构造器。这样做称为显式构造器调用(explicit constructor invocation。这是另一个Rectangle类,其实现与“ 对象”部分中的实现不同 。

  1. public class Rectangle {
  2. private int x, y;
  3. private int width, height;
  4. public Rectangle() {
  5. this(0, 0, 1, 1);
  6. }
  7. public Rectangle(int width, int height) {
  8. this(0, 0, width, height);
  9. }
  10. public Rectangle(int x, int y, int width, int height) {
  11. this.x = x;
  12. this.y = y;
  13. this.width = width;
  14. this.height = height;
  15. }
  16. ...
  17. }

此类包含一组构造器,每个构造器都会初始化矩形的一些或所有成员变量。构造器为参数未提供其初始值的任何成员变量提供默认值。例如,无参数构造器在坐标0,0处创建1x1的矩形 。有两参数的构造器调用四个参数的构造器,传入宽度和高度,但始终使用0,0坐标。和前面一样,编译器根据参数的数量和类型确定要调用的构造器(方法重载)。
如果存在,则另一个构造器的调用必须是该构造器的第一行。