this关键字
在java中,this能表示不同的意思。
如果在方法内部使用,则表示这个方法所属对象的引用。
如果在构造器内使用,表示该构造器正在初始化的对象。
this可以调用类的属性、方法、构造器。
为什么要使用this关键字
当在方法内需要用到调用该方法的对象时,就用this。
我们可以用this来区分属性和局部变量。
使用this关键字
注意this出现的位置
public class Student {
private Integer age;
private String name;
public Student() {
//this(10);
System.out.println("我是无参构造器");
}
public Student(Integer age) {
this();
this.age = age;
}
public Student(Integer age, String name) {
this(50);
this.age = age;
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void say(){
System.out.println(this.name);
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
Student student1 = new Student(18, "张三");
Student student2 = new Student(20, "李四");
student1.say(); // this 代表student1
student2.say(); // this 代表student2
}
}
首先我们可以看到构造器中可以使用this关键字来调用其它的构造器。但是,有几个需要注意的地方。
第一,this必须放在构造方法的第一行。
第二,两个构造器不能互相调用对方。
否则会引起递归调用,无法创建对象。就像我在无参构造器中注释的那一行,如果取消注释,就会报错。
其次就是当形参和成员变量重名时,必须在方法中使用this关键字来区分,this.属性表示是类的成员变量。就像setter方法中的this用法一样。
最后就是使用this访问属性和方法时,如果在本类中未找到,会从父类中查找,一直查找到Object 。
总结
this关键字可以这么理解,谁调用this所在的方法,this就是谁。Student的say()方法中就输出了this.name,但是根据this所指向的对象的不同,输出的name也是不同的。