Java 基础-this 关键字

this 关键字的应用

  1. 使用 this 关键字引用当前类的实例变量
  2. 使用 this 关键字调用当前类的实例方法
  3. 在构造方法中使用 this 关键字作为参数
  4. 使用 this 关键字作为方法调用中的参数传递
  5. 使用 this() 关键字调用当前类的其它构造方法(必须放在构造方法的第一行)
  6. 使用 this 关键字返回当前类的实例

image-20201107215347992

使用 this 关键字引用当前类的实例变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Test {
    int a;
    int b;

    Test(int a, int b) {
        this.a = a;
        this.b = b;
    }

    void display() {
        System.out.println("a = " + a + "  b = " + b);
    }

    public static void main(String[] args) {
        Test object = new Test(10, 20);
        object.display();
    }
}

a = 10 b = 20

使用 this 关键字调用当前类的实例方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Test {
    void display() {
        this.show();
        System.out.println("Inside display function");
    }

    void show() {
        System.out.println("Inside show funcion");
    }

    public static void main(String args[]) {
        Test t1 = new Test();
        t1.display();
    }
}

Inside show funcion Inside display function

在构造方法中使用 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
class A {
    B obj;

    A(B obj) {
        this.obj = obj;
        obj.display();
    }
}

class B {
    int x = 5;

    B() {
        A obj = new A(this);
    }

    void display() {
        System.out.println("Value of x in Class B:" + x);
    }

    public static void main(String[] args) {
        B obj = new B();
    }
}

Value of x in Class B:5

使用 this 关键字作为方法调用中的参数传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Test {
    int a;
    int b;

    Test() {
        a = 10;
        b = 20;
    }

    void display(Test obj) {
        System.out.println("a = " + obj.a + "  b = " + obj.b);
    }

    void get() {
        display(this);
    }

    public static void main(String[] args) {
        Test object = new Test();
        object.get();
    }
}

a = 10 b = 20

使用 this() 关键字调用当前类的其它构造方法(必须放在构造方法的第一行)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Test {
    int a;
    int b;

    Test() {
        this(10, 20);
        System.out.println("Inside default constructor");
    }

    Test(int a, int b) {
        this.a = a;
        this.b = b;
        System.out.println("Inside parameterized constructor");
    }

    public static void main(String[] args) {
        Test object = new Test();
    }
}

Inside parameterized constructor Inside default constructor

使用 this 关键字返回当前类的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Test {
    int a;
    int b;

    Test() {
        a = 10;
        b = 20;
    }

    Test get() {
        return this;
    }

    void display() {
        System.out.println("a = " + a + "  b = " + b);
    }

    public static void main(String[] args) {
        Test object = new Test();
        object.get().display();
    }
}

a = 10 b = 20

参考资料

本文作者:
本文链接: https://hgnulb.github.io/blog/98860960
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!