1. this关键字的作用
1— this代表所在类的当前对象的引用(地址值),即代表当前对象
2. this关键字的应用
1 用于普通的gettter与setter方法
this出现在实例方法中,谁调用这个方法(哪个对象调用这个方法),this就代表谁(this就代表哪个对象)
public class Student {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age > 0 && age < 200) {
this.age = age;
} else {
System.out.println("年龄非法!");
}
}
public int getAge() {
return age;
}
}
2-- 用于构造器中
public class Student {
private String name;
private int age;
// 无参数构造方法
public Student() {}
// 有参数构造方法
public Student(String name,int age) {
this.name = name;
this.age = age;
}
}
3.总结:
目标:this关键字的使用总结。
this关键字代表了当前对象的引用。
this可以出现在方法,构造器中。
this出现在方法中:哪个对象调用这个方法this就代表谁。
this可以出现在构造器中:代表构造器正在初始化的那个对象。
this可以区分变量是访问的成员变量还是局部变量。