2015-09-07 77 views
1

我也許一個愚蠢的問題,我想從方法訪問本地屬性,例如:獲得財產 - Java的

public class Example { 
    private int myprop; 
    public int getMyprop() { 
     return myprop; 
    } 

    public void setMyprop(int myprop) { 
     this.myprop= myprop; 
    } 

    public void useProperty(){ 
    // i want to use here the variable: 'myprop' how i can accomplish this? 
    } 
} 

感謝您的時間。

+0

修復你'get'方法。 –

+0

您可以直接或通過吸氣劑使用此變量(修復後)。 –

+0

對不起,如果我修復,我只是用我的get方法訪問變量? –

回答

1

您在getMyprop()中所做的相同方式:按名稱。

public void useProperty(){ 
    if (myprop == 42) { 
     System.out.println("It's the Answer to the Ultimate Question of Life, the Universe, and Everything"); 
    } 
} 
0

這很簡單。你可以不喜歡你的getter一個或者你可以用你的getter也:

//直接使用 「myprop」

public void useProperty(){ 
    // access directly "myprop" here 
    System.out.println("Access directly myprop: " + this.myprop); 

    } 

//或使用getter

public void useProperty(){ 
    // access by using getter 
    System.out.println("Access myprop via getter: " + this.getMyprop()); 
    } 

希望這有助於