在被调用对象的调用对象中设置变量

时间:2013-07-08 23:55:32

标签: java

在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
  }
}

1 个答案:

答案 0 :(得分:1)

传递对象的引用。

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

如果您正在使用nested classes(另一个类与另一个类具有隐含的父子关系),请使用:

OuterClass.this.setThisInt(5);

等等。