java关键字this

this的用途

当本地的局部变量和类的成员变量重名的时候,根据“最近原则”,优先使用局部变量。如果需要访问本类当中的成员变量,需要使用格式:

this.成员变量名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Person {
String name; // 自己的名字
Person(String name){
this.name = name;
}
// 参数name是对方名字
public void sayHello(String name){
System.out.println(name + ",你好。我是" + this.name);
}
}

public class Main2{

public static void main(String[] args) {
Person person = new Person("小明");
person.sayHello("花儿");
}
}

this是什么?

this是一个对象的自己的引用,通过谁调用的方法,谁就是this.

person.成员方法()

person即是this


java关键字this
https://blog.wangxk.cc/2020/08/18/java关键字this/
作者
Mike
发布于
2020年8月18日
许可协议