this的本质就是“当前对象的地址”;
this的用法:
- 普通方法中,this总是指向调用该方法的对象
- 构造方法中,this总是指向正要初始化的对象
- this不能用于static
- this作为普通方法的“隐式参数”,由系统传入方法中
public class TestThis {
int a,b,c;
TestThis() {
System.out.println("正要初始化一个对象");
}
TestThis(int a, int b) {
// TestThis(); // 这样是无法调用构造方法的
this(); // 调用无参的构造方法,并且位于首行;
this.a = a;
this.b = b;
System.out.println(this.a + "空格" + this.b);
}
TestThis(int a, int b, int c) {
this(a, b); // 构造函数调用其他有参数构造函数,且位于第一行
this.c = c;
}
void sing () {
}
void eat () {
this.sing(); // 调用本类中的sing()
System.out.println("你妈妈喊你回家吃饭");
}
public static void main(String[] args) {
TestThis t1 = new TestThis(2, 3);
t1.eat();
}
}