2015-09-07 79 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()); 
    } 

希望这有助于