[英]Java - Why do we use the “this” keyword in constructors?
我試着環顧四周,但很難找到“這個”。 但我似乎無法掌握這兩者之間的區別
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;
}
}
當你寫作
y = y;
z = z;
您只是將局部變量分配給自己,而根本不觸及實例變量。 由於y
引用局部變量,因此必須編寫this.y
以引用要分配的實例變量。
如果不想修改變量,你可以通過使變量final
來幫助捕獲這樣的錯誤。 例如:
x(final int y, final int z) {
this.y = y;
this.z = z;
}
如果你帶走了this.
前綴,您將收到編譯錯誤,因為無法更改局部變量y
和z
。
在Java中, this
關鍵字表示類的當前實例化。 所以當你創建一個對象時:
x obj = new x();
x
有兩個“實例”(非本地)變量y
和z
。
如果您的類也包含包含同名局部變量的方法,那么Java Runtime環境(計算機)如何知道您指的是哪個y
和z
? 例如:
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.