this的用法:
- 普通方法中,this总是指向调用该方法的对象。
- 构造方法中,this总是指向正要初始化的对象。
- this()调用重载的构造方法,避免相同的初始化代码。但只能在构造方法中用,并且必须位于构造方法的第一句。
- this不能用于static方法中。
this是作为普通方法的“隐式参数”,由系统传入到方法中。 ```java public class ThisTest { int a,b,c;
ThisTest(){
System.out.println("正在初始化一个Hello对象");
}
ThisTest(int a,int b){ // ThisTest(); //这样是无法调用构造方法的
this(); //调用上面那个无参构造方法 a=a; //这里都是指的局部变量而不是成员变量 //这样就区分了成员变量和局部变量,这种情况占了this使用情况的大多数 this.a=a; this.b=b;
}
ThisTest(int a,int b,int c){
this(a,b); //调用的上面那个包含2个参数的构造方法 this.c=c;
}
void sing(){ }
void eat(){
this.sing(); //调用本类中的方法 sing() System.out.println("你妈叫你回家吃饭了!!");
}
public static void main(String[] args) {
ThisTest thisTest=new ThisTest(2,3,4); thisTest.eat();
} }
```