在java中,编译器会为每个对象分配一个this关键字。在代码中使用关键字可以使代码更优雅。下面我就列举一下this关键字常见的几种场景。
1、this代表当前对象调用成员变量和方法,也是用的最多的地方。
1 package demo; 2 /** 3 * 测试this代表当前对象调用成员变量和方法 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private String name; 9 private int age; 10 11 void eat(){ 12 System.out.println("刘二狗正在吃饭!"); 13 } 14 15 void print(String name,int age){ 16 this.name = name; //区分成员变量和参数 17 this.age = age; 18 this.eat(); //this代表当前对象 19 System.out.println(name + "今年" + age); 20 } 21 22 public static void main(String[] args) { 23 //初始化对象的时候就会调用无参构造器 24 TestThis tt = new TestThis(); 25 tt.print("刘二狗",18); 26 } 27 }
打印结果:
2、代表当前对象的句柄,如果你希望将句柄返回给当前对象,就可以在return中使用。也就是说当你使用某个对象执行一个方法,需要在方法内执行逻辑代码,但是最后又希望拿到该对象的句柄并对同一对象执行多项操作。
1 package demo; 2 /** 3 * 测试this代表当前句柄并返回给当前对象 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private int i = 0; 9 //返回当前对象的方法 10 TestThis test(){ 11 //执行这个方法,我们可以在里面做大量的操作之后再把句柄返回给当前对象 12 i++; 13 return this; 14 } 15 //打印的方法 16 void print(){ 17 System.out.println("i = " + i); 18 } 19 20 public static void main(String[] args) { 21 TestThis tt = new TestThis(); 22 tt.test().test().test().print(); 23 } 24 }
打印结果:
3、若同一个类中写了多个构造器,我们可能需要在一个构造器里调用另一个构造器。为了避免写重复的代码使程序更优雅,我们使用this可以做到。this不能调用两个构造器。
代码如下:
1 package demo; 2 /** 3 * 测试this在构造器里面调用其他构造器 4 * @author dyf 5 * 6 */ 7 public class TestThis { 8 private int count = 0; 9 private String str = new String("null"); 10 11 TestThis(int num){ 12 count = num; 13 System.out.println("带有整形参数的构造器"+count); 14 } 15 16 TestThis(String s){ 17 System.out.println("带有字符串参数的构造器"+s); 18 } 19 20 TestThis(String str,int number){ 21 this(number); //调用带有整形参数的构造器 22 //this(ss); //不能在一个构造器里面同时调用两个构造器 23 //为了避免成员变量str和参数str混淆,使用this可以避免 24 this.str = str; 25 this.count = number; 26 System.out.println("String && int args"); 27 } 28 29 TestThis(){ 30 this("hello",18);//调用带有两个参数的构造器 31 System.out.println("无参构造器"); 32 } 33 34 void print(){ 35 System.out.println("count = " + count + " --- " + "str = " + str); 36 } 37 38 public static void main(String[] args) { 39 //初始化对象的时候就会调用无参构造器 40 TestThis tt = new TestThis(); 41 tt.print(); 42 } 43 }
打印结构: