关键字 this 是用来指向当前对象或类实例的,可以用来点取成员。
this.day 指的是调用当前对象的 day 字段,示例如下: public class MyDate { private int day, month, year; public void tomorrow() { this.day = this.day + 1; // 其他代码 } }
Java 编程语言自动将所有实例变量和方法引用与 this 关键字联系在一起,因此,使用关键字在某些情况下是多余的。下面的代码与前面的代码是等同的。 public class MyDate { private int day, month, year; public void tomorrow() { day = day + 1; // 在 day 前面没有使用 this // 其他代码 } }
区分同名变量 在类属性上定义的变量和方法内部定义的变量相同的时候,到底是调用谁?例如: public class Test { int i = 2; public void t() { int i = 3; // 跟属性的变量名称是相同的 System.out.println(“实例变量 i=” + this.i); System.out.println(“方法内部的变量 i=” + i); } } 输出结果: 实例变量 i=2 方法内部的变量 i=3
也就是说:“this.变量”调用的是当前属性的变量值,直接使用变量名称调用的是相对距离最近的变量的值。
作为方法名来初始化对象 也就是相当于调用本类的其它构造方法,它必须作为构造方法的第一句。示例如下: public class Test { public Test() { this(3);// 在这里调用本类的另外的构造方法 } public Test(int a) {} public static void main(String[] args) { Test t = new Test(); } }
作为参数传递 需要在某些完全分离的类中调用一个方法,并将当前对象的一个引用作为参数传递时。例如: Birthday bDay = new Birthday (this);