- 在实例方法中出现this关键词时,表示正在调用该对象的当前对象。
- 说明:
1)当实例变量名与局部变量名相同时,成员变量前必须有this.或者类名. ,不可省略。
class A{
int x;
static int y;
void f(){
int x=90;
int y=89;
this.x=100;
A.y=200;
System.out.println(x+" "+this.x); //90 100
System.out.println(y+" "+A.y); //89 200
}
……
- 应用:
1)形参规范问题:
class student{
String name;
int age;
String sex;
Student(String name,int age,String sex){
this.name=name;
this.age=age;
this.sex=sex;
} //据说这样比较符合程序员的美?
2)相似构造方法的调用(this语句,必须是构造方法中的第一条语句)
class Student{
String name;
int age;
char sex;
Student(String name){
this() //可省略
this.name=name;
}
Student(String name,int age){
this(name);
this.age=age;
}
Student(String name,int age,char sex){
this(name,age);
this.sex=sex;
}
}
……