2013-05-01 81 views
6

我爲我的微不足道的和可能愚蠢的問題表示歉意,但是我對使用方法或訪問某些東西時何時使用「this」前綴有些困惑。什麼時候在Java中使用「this」

例如,如果我們看一下#4 這裏: http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf

我們的解決方案看這裏: http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf

我們看到一個解決方案,A部分)是

public int countWhitePixels() { 
int whitePixelCount = 0; 
    for (int[] row : this.pixelValues) { 
     for (int pv : row) { 
     if (pv == this.WHITE) { 
     whitePixelCount++; 
     } 
    } 
    } 
return whitePixelCount; 
} 

而另一種解決方案是

public int countWhitePixels() { 
int whitePixelCount = 0; 
    for (int row = 0; row < pixelValues.length; row++) { 
     for (int col = 0; col < pixelValues[0].length; col++) { 
     if (pixelValues[row][col] == WHITE) { 
     whitePixelCount++; 
    } 
    } 
} 
return whitePixelCount; 
} 

這是我的問題。爲什麼他們使用「這個」。在第一個解決方案中訪問pixelValues甚至WHITE時的前綴,但不是第二個?我認爲「這個」是隱含的,所以我正確地說「這個」。第一個解決方案沒有必要?

非常感謝你的幫助:)

+0

Termionogly請。 Java中沒有'命令','this'不是其中之一。 – EJP 2013-05-01 10:18:33

回答

1

當一個方法參數的名稱相同類的數據成員之一;那麼,要提及數據成員,必須先輸入this.。例如,在功能setA()

public void setA(int a) 
{ 
    this.a = a; 
} 

由於兩個數據成員和方法的papameter被命名爲a,引用數據成員,你必須使用this.a。在其他情況下,這不是必需的。

而就你而言,我不認爲有必要使用this,儘管使用它並沒有什麼壞處。

0

this指的是類本身的實例。例如:

private String name, car; 

public class Car(String name, String color) 
{ 
    this.name = name; 
    this.color = color; 
} 
6

隨着this,你明確地提及你所在的對象實例。您只能在實例方法或初始化程序塊中執行此操作,但不能在static方法或類初始化程序塊中執行此操作。

當你需要這個?

僅當同名變量(局部變量或方法參數)爲時隱藏聲明。例如:

private int bar; 
public void setBar(int bar) { 
    this.bar = bar; 
} 

這裏的方法參數是隱藏實例屬性。

當編碼器用它來使用它嗎?

爲提高可讀性,程序員在訪問實例屬性之前預先配置this.限定符是一種常見做法。例如。:

public int getBar() { 
    return this.bar; 
    // return bar; // <-- this is correct, too 
} 
+2

+1製作包括「可讀性」。 我認爲代碼的可讀性不能強調。 在這個例子中(一個簡單的訪問器方法)它可能是矯枉過正的,但是在很多情況下它可以大大提高可讀性。 – GreyBeardedGeek 2013-05-01 01:56:57

+0

IMO'return this.bar;'不如'return bar;'可讀性強。它只是更混亂。 – 2013-05-01 02:00:24

+0

同意@SteveKuo,您應該讓IDE通過顏色方案來區分局部變量和類屬性,而不是每次都手動放置'this.'關鍵字而不是實際使用,而不是添加冗長。 @GreyBeardedGeek:你使用記事本或_proper_ IDE進行開發嗎? ;-) – klaar 2015-10-21 07:32:54

4

The Java™ Tutorials

使用這種具有場

使用該關鍵字的最常見的原因是因爲一個域是通過方法或構造參數陰影

例如,Point類是這樣寫的

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

    //constructor 
    public Point(int a, int b) { 
     x = a; 
     y = b; 
    } 
} 

,但它也可以寫成這樣:

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

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