[英]Is the use of the “this” keyword superfluous? Java
我一直在互聯網上和那里進行一些研究,我想我幾乎可以理解this
關鍵字的工作方式。 我的問題是: this
什么時候是必要的功能?
我知道,區分對象的私有實例變量和設置為完全相同名稱的另一個變量很有用。 例:
public class SomeObject {
private int someNum;
public SomeObject() {}
public setSomeNum(int someNum) {
this.someNum = someNum;
}
}
我還從第二個答案@ using-the-wordword-this-in-java中得知,它用於訪問“嵌套”類。 盡管我還沒有嘗試過,但這似乎是一個很酷的主意。
這個問題是如何發生的:我正在編寫一個class
, class
通過一系列屬性定義游戲角色:
public class Charact {
private String name;
// A ton of other private variables that represent character stats.
public Charact() {} // This one is for the main character.
public Charact(String name, /*All of the other variable parameters*/) { // This one is used for making NPCs.
this.name = name;
// Setting of all of the other variables.
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
// All of the other getter and setter methods.
}
因此,這里有一些關於我的代碼的問題(與我的最初問題相切):
正在使用this調用setter方法,例如this.setVariable(variable);
,是多余的,因為它將執行與setVariable(variable);
相同的setVariable(variable);
?
我專門用大寫字母聲明了所有私有實例變量,從而避免了在setter中使用this
。 我這樣做(我是否違反了任何常規的命名約定?)還是應該在設置器中使用小寫的變量名,而this
應該對嗎?
使用this
是否有助於識別正在引用的類的實例,或者該實例已被計算機隱含,這意味着確實不需要this
實例?
任何可以提供詳盡闡述的答案都將非常有幫助,因為我上周才開始制作非靜態課程。 另外,這是我的第一個問題,因此,如果不是真的使用正確的格式詢問它,我將感到抱歉。
我認為您已經了解了this
的用途。 當您需要明確說明所指的內容時,可以使用它。
這是一個新穎的例子。 (實際上並沒有編寫這樣的類。它只是用來顯示this
用法。)
class Outer {
int value; /* #1 */
class Inner {
int value; /* #2 */
void setInnerValue(int value /* #3 */) {
// #2 #3
// vvvvv vvvvv
this.value = value;
}
void setOuterValue(int value /* #4 */) {
// #1 #4
// vvvvv vvvvv
Outer.this.value = value;
}
}
}
如果不需要限定您所引用的內容,那么是多余的。
this
也用於調用鏈中的構造函數。
class Example {
Example() { this(1); }
Example(int i) { }
}
我違反任何常規的命名約定嗎?
是的,你是。 Java中的標識符按慣例以小寫字母開頭(除非它們是static final
常量,通常都是大寫的)。 您應該遵循約定。
像this.setVariable(variable)
這樣,用this調用setter方法通常是多余的,但卻是很好的實踐。
用大寫字母聲明任何變量會使所有可能不得不維護您的代碼的所有其他Java程序員感到困惑。 我們采用慣例是有充分理由的。 當所有變量看起來都像類時,它最終也會使您感到困惑,並且您無法從實例化中分辨出靜態調用。
this
暗含了this object
。
編輯:以上句子已從this class
更改
使用它很方便,因為稍后您將擁有諸如super之類的東西。 如果您不在那里使用super並且不使用它,那么您將得到混亂的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.