55.md 2.3 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4
# 使用`this`关键字

> 原文: [https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html](https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html)

W
wizardforcel 已提交
5
在实例方法或构造器中,`this`是对*当前对象*的引用 - 正在调用其方法或构造器的对象。您可以使用`this`从实例方法或构造器中引用当前对象的任何成员。
W
init  
wizardforcel 已提交
6 7 8

## 将`this`与 Field 一起使用

W
wizardforcel 已提交
9
使用`this`关键字的最常见原因是因为字段被方法或构造器参数遮蔽。
W
init  
wizardforcel 已提交
10 11 12

例如,`Point`类是这样写的

W
wizardforcel 已提交
13
```java
W
init  
wizardforcel 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

```

但它可能是这样写的:

W
wizardforcel 已提交
29
```java
W
init  
wizardforcel 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

```

W
wizardforcel 已提交
43
构造器的每个参数都会影响对象的一个​​字段 - 构造器 **`x`** 内部是构造器的第一个参数的本地副本。要引用`Point`字段 **`x`** ,构造器必须使用`this.x`
W
init  
wizardforcel 已提交
44

W
wizardforcel 已提交
45
## 将`this`与构造器一起使用
W
init  
wizardforcel 已提交
46

W
wizardforcel 已提交
47
在构造器中,您还可以使用`this`关键字来调用同一个类中的另一个构造器。这样做称为*显式构造器调用*。这是另一个`Rectangle`类,其实现与 [Objects](../javaOO/objects.html) 部分的实现不同。
W
init  
wizardforcel 已提交
48

W
wizardforcel 已提交
49
```java
W
init  
wizardforcel 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
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;
    }
    ...
}

```

W
wizardforcel 已提交
71
该类包含一组构造器。每个构造器都初始化一些或所有矩形的成员变量。构造器为任何成员变量提供默认值,其初始值不是由参数提供的。例如,无参数构造器在坐标 0,0 处创建 1x1 `Rectangle`。双参数构造器调用四参数构造器,传递宽度和高度,但始终使用 0,0 坐标。和以前一样,编译器根据参数的数量和类型确定要调用的构造器。
W
init  
wizardforcel 已提交
72

W
wizardforcel 已提交
73
如果存在,则另一个构造器的调用必须是构造器中的第一行。