Java零基础-this 关键字

  1. this 是一个引用,是一个变量,这个变量保存了指向自身的内存地址

  2. this 存储在 JVM 堆内存 Java 对象内部;

  3. 创建 100 个 Java 对象,每一个对象都有 this ,也就是说有 100 个不同的 this

  4. this 可以出现在“实例方法”中,指向当前正在执行这个动作的对象(**this 代表当前对象**);

  5. 在多数情况下都是可以省略不写的,用来区别局部变量和实例变量时,不能省略

    1
    2
    3
    4
    5
    6
    7
    private int id;

    public void setId(int id) {
    // 不可以采用这种方式
    // id = id;
    this.id = id;
    }
  6. 不能使用在带有 static 的方法中

    在带有 static 的方法中不能“直接”访问实例变量和实例方法,因为实例变量和实例方法都需要对象存在。而static 的方法中是没有 this 的,也就是说当前对象是不存在的,自然无法访问当前对象的实例变量和实例方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public class ThisText01 {
    // 实例变量
    String name;

    // 实例方法
    public void doSome() {
    }

    // 带有 static
    public static void main(String[] args) {
    // 没有 this
    // System.out.println(name)
    // doSome()

    ThisText01 tt = new ThisText01();
    System.out.println(tt.name);
    tt.doSome();
    }
    }
  7. this用在哪?

    • 可以使用在实例方法当中,代表当前对象【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
package test0215;

public class ThisText02 {

// 没有 static 的变量
int i = 10;

// 带有 static 的方法
public static void doSome() {
System.out.println("do some!");
}

// 没有 static 的方法
public void doOther() {
System.out.println("do other!");
}

// 带有 static 的方法
public static void method1() {
// 调用 doSome
// 使用完整方式调用
ThisText02.doSome();
// 使用省略方式调用
doSome();

// 调用 doOther
// 使用完整方式调用
ThisText02 tt1 = new ThisText02();
tt1.doOther();
// 使用省略方式调用

// 访问 i
// 使用完整方式调用
System.out.println(tt1.i);
// 使用省略方式调用
}

// 没有 static 的方法
public void method2() {
// 调用 doSome
// 使用完整方式调用
ThisText02.doSome();
// 使用省略方式调用
doSome();

// 调用 doOther
// 使用完整方式调用
this.doOther();
// 使用省略方式调用
doOther();

// 访问 i
// 使用完整方式调用
System.out.println(this.i);
// 使用省略方式调用
System.out.println(i);
}

public static void main(String[] args) {
// 要求在这里编写程序调用 method1
// 使用完整方式调用
ThisText02.method1();
// 使用省略方式调用
method1();

// 要求在这里编写程序调用 method2
// 使用完整方式调用
ThisText02 tt = new ThisText02();
tt.method2();
// 使用省略方式调用

}

}