关键字this的用法总结:
- 当局部变量与成员变量相同时,用this表示成员变量以示区分;
- this关键字将当前对象传给其他方法;(相关例子在Java编程思想的P85)
- 当需要返回当前对象的引用时,需要使用return this;(好处:当你使用一个对象调用该方法时,该方法返回的是经过修改的对象,且又能使用该对象进行其他操作)
- 传递多个参数;
- 在构造器中调用构造器,需要使用this;举例如下:
-
public class Flower { int petalCount=0; String s="initial value"; Flower(int petals){ petalCount=petals; System.out.println("只有int类型的参数的构造函数"+"petalCount="+petalCount); } Flower(String ss){ s=ss; System.out.println("只有String类型的参数的构造函数"+"s="+s); } Flower(String s,int petals){ this(s);//this(petal); this.petalCount=petals; System.out.println("有String和int类型的参数的构造函数"); } Flower(){ this("hi",12); System.out.println("默认构造函数"); } void print(){ System.out.println("petalCount="+petalCount+"s="+s); } public static void main(String[] args) { // TODO Auto-generated method stub Flower flower=new Flower(); flower.print(); } }
分析:从主函数开始,new了一个新的内存空间,初始化对象,即调用构造函数,此处无参数,即调用默认构造函数,在默认的构造函数中,this(“hi”,122);相当于无参构造函数又去调用含有两个参数的构造函数,而两个参数的构造函数中this(s);又去调用含有一个String类型参数的构造函数;然后打印,再一步步返回去,打印各自内容。
注:
- this表示当前对象的引用;
- 表示用类的成员变量,而不是函数参数;
- 用于在构造方法中引用满足指定参数类型的构造器(构造方法),只能引用一个构造方法,且必须位于开始;
- this不能用在static方法中(因为this指代当前对象,而static无对象一说)