使用this关键字

原文: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

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

this与 Field 一起使用

使用this关键字的最常见原因是因为字段被方法或构造器参数遮蔽。

例如,Point类是这样写的

  1. public class Point {
  2. public int x = 0;
  3. public int y = 0;
  4. //constructor
  5. public Point(int a, int b) {
  6. x = a;
  7. y = b;
  8. }
  9. }

但它可能是这样写的:

  1. public class Point {
  2. public int x = 0;
  3. public int y = 0;
  4. //constructor
  5. public Point(int x, int y) {
  6. this.x = x;
  7. this.y = y;
  8. }
  9. }

构造器的每个参数都会影响对象的一个​​字段 - 构造器 x 内部是构造器的第一个参数的本地副本。要引用Point字段 x ,构造器必须使用this.x

this与构造器一起使用

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

  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 Rectangle。双参数构造器调用四参数构造器,传递宽度和高度,但始终使用 0,0 坐标。和以前一样,编译器根据参数的数量和类型确定要调用的构造器。

如果存在,则另一个构造器的调用必须是构造器中的第一行。