一、this 关键字说明
1、this
代表实例(或对象),也就是 new
的时候的实例;
2、this.属性
:使用属性;
3、this.函数
:调用方法;
大部分的时候,我们在类中不需要显示使用 this.
,因为默认会有 this.
加在属性或函数的前面,只是不显示出来;
如果方法里有个局部变量和成员变量同名,在方法中则需要使用 this.
,用于区分使用的是类的变量;
二、编程实战
代码的详细解读,可以参考视频教程
/**
* User: 祁大聪
*/
public class Person {
private String name;
private int age;
public String getName(){
// return name; // 这里隐藏了 this. ,指的是类中的 name 属性
return this.name; // 使用 this. ,和上面的写法没有区别
}
public void setName(String name){
//这里必须使用 this. ,不然无法区分局部变量 name(参数),和类的属性 name
this.name = name;
}
public static void main(String[] args){
Person sanNi = new Person();
/**
* 这里面 sanNi 就是上面的 this
* 每个不同的实例,对应不同的 this
* 所以this就是实例
*/
sanNi.getName();//调用getName函数
}
}