8.3 this关键字的作用

当方法的局部变量和类的成员变量重名的时候,根据"就近原则",优先使用局部变量

如果需要访问本类当中的成员变量,需要使用格式:

this.成员变量名

通过谁调用的方法,谁就是this:

代码示例:

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

}

  

public class Demo01Person {
    public static void main(String[] args) {
        Person person = new Person();
        person.name="王建林";
        person.sayHello("王思聪");
        System.out.println(person);//打印的是地址值
    }

}

  

执行结果:

猜你喜欢

转载自www.cnblogs.com/sdrbg/p/11110403.html
8.3