其实重点就一句话:this指代当前对象
this的三种用法
this.属性名
一个方法当中的局部变量和成员变量名称相同,我们的程序需要在这个方法当中访问成员变量,这个时候就必须使用this关键字,用来区分成员变量和方法当中的参数。例如,set方法
public void setName(String name) {
this.name = name;
}
this.方法名
让类中的一个方法来访问类中的另一个方法或者实例变量
public void souPerson() {
System.out.println("我是一个人");
}
public void name() {
this.souPerson();
}
public static void main(String[] args) {
Person person = new Person();
person.souPerson();
}
this()
this()可以用来访问本类的构造方法
public Person(String name,int age) {
this.age = age;
this.name = name;
}
public Person() {
this("张三",10);
}
需要注意的是:
this()不能在普通方法中使用,只能在构造方法中使用
this()在构造方法中使用必须是第一条语句
不能与super()同时使用
另外staic修饰的方法中不能使用this,
因为static关键字是对类而言的,this关键字是指当前对象。