this是Java的一个关键字,表示某个对象。this可以出现在实例方法和构造方法中,但不可以出现在类方法中。
class A{
int x;//相当于 this.x
static int y;
void f(){
this.x = 100;
A.y = 200;
}
}
上述A类中的实例方法f中出现了this,this就代表使用f的当前对象,“this.x”就表示当前对象的变量x,当对象调用方法f时,将100赋值给该对象的变量x。
因此,当一个对象调用方法时,方法中的实例成员变量就是指分配给该对象的实例成员变量,而static变量和其他对象共享。因此,通常情况下,可以省略实例成员变量名字前面的“this.”以及static变量前面的“类名.”。
即:
class A{
int x;
static int y;
void f(){
x = 100;
y = 200;
}
}
但是,当实例变量成员变量的名字和局部变量的名字相同时,成员变量前面的“this.”或“类名.”就不可省略。
即:
class A{
int x;
static int y;
void f(int x){
this.x = x;//this.x为实例变量x,x为局部变量x。
y = 200;
}
}
注:this不能出现在类方法中,这是因为类方法可以通过类名直接调用,这时,可能还没有任何对象诞生。
为了更好的理解以上讲解,提供练习代码如下:
class B{
int x = 100,y = 200;
public void setX(int x){
x = x;
}
public void setY(int y){
this.y = y;
}
public int getXYSum(){
return x+y;
}
}
public class A{
public static void main(String args[]){
B b = new B();
b.setX(-100);
b.setY(-200);
System.out.println("sum="+b.getXYSum());
}
}
输出结果:
sum=-100