2014-12-03 44 views
1
public class MyClass { 

    private char e; 

    public void intializeVariable(char z) { 
     this.e = z; 
    } 
    public void intializeVariableWithoutThis(char z) { 
     e = z; 
    } 

    public static void main(String[] args) { 
    MyClass mC = new MyClass(); 
     System.out.println(mC.e); 
     mC.intializeVariable('m'); 
     System.out.println(mC.e); 
     mC.intializeVariableWithoutThis('n'); 
     System.out.println(mC.e); 
    } 

} 

方法initializeVariable設置私有變量和initailizeVariableWithoutThis正在做我只是想了解是什麼在設定使用值this.e = Z的區別一樣的東西之間的區別只是做e = z是什麼使用該運營商與正常分配

回答

2

沒有區別,但如果您使用相同名稱的參數爲類變量,那麼你必須使用這個鍵盤

public void intializeVariable(char e) { 
    this.e = e; 
} 
+0

啊,我明白了。得到它了。非常感謝。 – 2014-12-03 23:49:33

+0

不客氣,是的其他答案來了,當我一直在輸入這個答案,我沒有看到他們之前發佈這個答案 – jfun 2014-12-03 23:54:25

+0

那沒關係。你永遠不知道一些答案是否可能有一些額外的信息。而且我還必須等到7分鐘纔將一個標記爲正確的。 – 2014-12-03 23:59:45

4

這是用來表示當前對象的一個​​字段。

public void intializeVariable(char z) { 
    this.e = z; 
} 

如果更改上面的方法

public void intializeVariable(char e) { 
    this.e = e; 
} 

這將正常工作。編譯器會知道「e」是參數,this.e是對象的字段。

+0

非常感謝。我現在明白了。 – 2014-12-03 23:49:59

3

對於您的示例,沒有差異,因爲它們中的每個都將z指定爲e

只有參數的名稱與實例變量的確切名稱相同時,纔會有所不同。都被命名爲e

public void initializeVariableSameName(char e){ 
    this.e = e; 
} 

在這種情況下,e指參數e而不是實例變量e。它會影響實例變量e。這意味着訪問實例變量的唯一方法是用this(例如, this.e

另一種情況:

e = e; 

將參數e分配給自身;沒有用處。

+0

非常感謝,非常感謝。 – 2014-12-03 23:51:52

1

在這種情況下,你不需要直接說ethis.實例的字段之一,因爲在當前範圍內沒有其他變量,稱爲e,因此您可以跳過this.部分(它將由編譯器自動添加)。但是,如果你的方法的簽名看起來像

public void intializeVariable(char e) { 
    .. 
} 

願與您指定的值e參數e你就需要把它寫成

this.e = e; 
// ^ ^-- methods local variable 
// | 
// +------ field 
0

引用傳遞oracle docs 最使用此關鍵字的常見原因是因爲字段被方法或構造函數參數遮蔽。

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

    //constructor 
    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.