关于this关键字的使用:
1、this的单独使用:
(1)每实例化一个对象就会实例化一个this。
(2)this是一个对象中隐藏的引用变量,它保存了当前对象的内存地址,指向自身。
(3)this存储在堆内存当中对象的内部。
(4)this只能使用在实例方法中。谁调用这个实例方法,this就是谁。显然静态方法中不能使用this,因为静态方法的调用不需要实例化对象的参与。
(5)this大部分时候可以省略,在实例方法中,或者构造方法中,为了区分实例变量与局部变量,这种情况下,this不能省略。
2、this()的使用:
新语法,如果当前的构造方法区调用另一个本类中的构造方法时,可以使用this(参数列表),也就是当前构造方法的代码和被调用的构造方法里的代码类似时,在当前构造方法中使用this(参数列表),实现代码复用。
注意:在构造方法,this()只能出现的第一行,并且每个构造方法中最多只能有一个this()。
测试代码:
public class MyTest{
public static void main(String[] args) {
Animal a1 = new Animal();
System.out.println(a1.getName()); //输出:未知动物
Animal a2 = new Animal("Cat");
System.out.println(a2.getName()); //输出:Cat
}
}
class Animal {
//封装私有属性:名字
private String name;
//setter and getter
public void setName(String name) {
this.name = name; //当局部变量与类中属性变量名一样,此时this不能省略
}
public String getName() {
return name;
}
//构造函数
public Animal() {
this("未知动物"); //调用另一个构造方法,this()只能出现在构造方法的第一行
}
public Animal(String name) {
this.name = name;
}
}