This 关键字

This 关键字

在实例方法或构造函数中,this是对当前对象的引用 (当前对象:正在调用其方法或构造函数的对象。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
举例:
1. 与 field 一起使用:
通常是发生了遮蔽(特定作用域中(例如在构造函数中)出现了与外部作用域中相同名称的变量名(如下例子),导致在这个特定作用域中定义的同名变量隐藏了外部的同名变量,这时如果要使用外部变量就不能直接使用变量名,需要用 this 关键字)
// 原因是 构造函数的参数与field重名,导致被遮蔽(shadow),所以通过 this,表明是要赋值给 Point 类中的field。
public class Point {
public int x = 0;
public int y = 0;

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

public class ShadowTest {

public int x = 0;

class FirstLevel {

public int x = 1;

void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
// 通过所属的类名引用包含较大作用域的成员变量
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
运行结果:
x = 23
this.x = 1
ShadowTest.this.x = 0

2. 与 构造函数一起使用:
// 这里希望提供有默认值的构造函数,使用时根据参数个数选择合适的构造函数;
// 注意,使用时 this(xxx) 需要写在构造函数的第一行
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;
}
...
}

3. ThreadLocal 中的例子:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
// 这里的 this 是调用get() 方法的对象的引用
ThreadLocalMap.Entry e = map.getEntry(this);
...
}

// 3中的具体使用,this 就是 threadLocalName 对象的引用
ThreadLocal<String> threadLocalName = ThreadLocal.withInitial(() -> Thread.currentThread().getName());
threadLocalName.get()
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2023 ligongzhao
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信