Java - 为什么我们使用"这个"构造函数中的关键字?

时间:2014-05-14 00:49:04

标签: java

我试过环顾四周,但很难找到“这个”。但我似乎无法把握这两者之间的区别

public class x{
int y = 0;
int z = 0;

x(int y, int z){
    y = y;
    z = z
    }
}

public class x{
int y = 0;
int z = 0;

x(int y, int z){
    this.y = y;
    this.z = z;
   }
}

2 个答案:

答案 0 :(得分:12)

写作时

y = y;
z = z;

您只是将局部变量分配给自己,而根本不触及实例变量。由于y引用局部变量,因此您必须编写this.y来引用要分配的实例变量。

如果您的变量final不打算修改,您可以帮助捕获这样的错误。例如:

x(final int y, final int z) {
    this.y = y;
    this.z = z;
}

如果你带走this.前缀,你将收到编译错误,因为无法更改局部变量yz

答案 1 :(得分:1)

在Java中,this关键字表示类的当前实例化。所以当你创建一个对象时:

x obj = new x();

x有两个“实例”(非本地)变量yz

如果您的类也包含包含同名局部变量的方法,那么Java Runtime环境(计算机)如何知道您指的是哪个yz?例如:

x(int y, int z){
    y = y; //Both z are just the local variables 
           //of this method and don't change the class.
    z = z; //Both z are just the local variables and dont affect class object
}

但是,如果执行以下操作,则更改对象y值,但不更改其z值:

x(int y, int z){
    this.y = 50; //call this function sets the objects y value to 50
    z = z; //But nothing happens to the objects z value because the
           //Java Runtime enviornment sees the z and finds its nearest
           //scope which is the method its defined in and thus the local
           //variable gets set to itself and then deleted after the method
           //is called and the object's z value is not changed.
}