2013-07-08 59 views
0

在Java中,如何从调用的对象中设置调用对象中的变量?我想我可以建立某种结构类的,但可有人告诉我,如果有一个更简单的方式做到这一点,如下面的伪代码进行一些修改:到对象的引用从调用对象调用对象中设置变量

public class Example(){ 
    int thisInt; 
    int thatInt; 

    public static void main(String[] args){ 
    Another myAnother = new Another(); 
    } 
    setThisInt(int input){thisInt=input;} 
    setThatInt(int input2){thatInt=input2;} 
} 

public class Another(){ 
    void someFunc(){ 
    this.Example.setThisInt(5);//I know this syntax is wrong 
    this.Example.setThatInt(2);//I know this syntax is wrong 
    } 
} 
+0

你能解释一下你做这个的原因吗?我期望您的原始问题还有其他解决方案符合常见的面向对象编程实践。 –

回答

1

通行证。

public class Another{ 
    void someFunc(Example ob){ 
    ob.setThisInt(5); 
    ob.setThatInt(2); 
    } 
} 

如果你使用nested classes(其它内一类有一个隐含的父子关系),用途:

OuterClass.this.setThisInt(5); 

等。

+0

+1为快速回答。谢谢。惊人的响应时间。 – CodeMed

+0

@CodeMed是的,我一直在选项卡中打开[this](http://stackoverflow.com/questions/tagged/java?sort=newest&pagesize=30)。真的很方便。 – hexafraction