Java学习笔记(七):this关键字的几种用法

this关键字的用法

this关键字主要有三个应用:
(1)this调用本类中的属性,也就是类中的成员变量
当成员变量和局部变量重名时,在该方法中使用this关键字,表示的是该方法所在类中的成员变量。
(2)this调用本类中的其他方法
(3)this调用本类中的其他构造方法


一、this调用本类中的属性,也就是类中的成员变量
代码说明:

 public class ThisDemo {
    int a=1,b;
    public void add(int a,int b) {
        System.out.println(a);
        System.out.println(this.a);
        this.a=a;
        this.b=b;
    }
    public static void main(String[] args) {
        ThisDemo t=new ThisDemo();
        t.add(10, 24);
        System.out.println(t.a+"  "+t.b);
    }
}

执行结果:
10
1
10 24

二、this调用本类中的其他方法

public class ThisDemo {
int a=1,b;
public ThisDemo add(int a,int b) {
    this.a=a;
    this.b=b;
    return this;
}
public static void main(String[] args) {
    ThisDemo t=new ThisDemo();
    System.out.println(t.add(2, 3));
    }
}

执行结果:
这里写图片描述

三、this调用本类中的其他构造方法

public class ThisDemo {
    int a=1,b;
    public ThisDemo(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public ThisDemo() {
        this(2,3);
    }
    public static void main(String[] args) {
        ThisDemo t=new ThisDemo();
        System.out.println(t.a+"  "+t.b);
    }
}

运行结果:2 3

注意:

1)this()调用其他构造方法的语句只能放在构造方法(在其他普通方法里是不行的)的首行。

2)在使用this调用其他构造方法的时候,至少有一个构造方法是不用this调用的。

猜你喜欢

转载自blog.csdn.net/qq_37239695/article/details/81290652