this关键字的作用

/*
当方法的局部变量和类的成员变量重名的时候,根据"就近原则 ",优先使用局部变量。
如果需要访问本类当中的成员变量,需要使用格式:
this.成员变量名

重点:通过谁调用的方法,谁就是 this
*/
public class Demo04 {
    String name;  //我自己的名字

    //参数 name是对方的名字
    //成员变量 name 是自己的名字
    public void sayHello(String name){
        System.out.println(name + ",你好,我是" + this.name);

    }
}
public class Demo04Person {
    public static void main(String[] args) {
        Demo04 person = new Demo04();
        person.name = "王健林";   //等于 this.name
        person.sayHello("王思聪");
    }
}

 

posted @ 2020-07-15 10:59  美女爱找茬  阅读(136)  评论(0编辑  收藏  举报