this关键字-CSDN博客

54 阅读1分钟
public class TestThis{
    TestThis(){
        //在构造方法中this代表当前正在构造的对象
        System.out.println("TestThis(): this = " + this);
    }
    //this关键字可以看做是该方法的一个形参,用于接收调用对象代表的实参
    void show(){
        //在成员方法中this代表当前正在调用的对象
        System.out.println("show(): this = " + this);
    }

    public static void main(String[] args){

         TestThis tt = new TestThis();
         tt.show();
         System.out.println("main方法中:tt = " + tt);

         TestThis tt2 = new TestThis();
         tt2.show();
         System.out.println("main方法中:tt2 = " + tt2);

    }
}

对于构造方法来说,this关键字就代表当前正在构造的对象
对于成员方法来说,this关键字就代表当前正在调用的对象

使用场景:
(1)当形参变量名和成员变量名相同时,在方法体的内部会优先选择形参变量使用,此时就需要使用this.的方式明确要求使用的是成员变量而不是形参变量。
(2)在构造方法的第一行使用this(实参)的方式可以调用本类中的其他构造方法。