在 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
}
}
最佳答案
传入对象的引用。
public class Another{
void someFunc(Example ob){
ob.setThisInt(5);
ob.setThatInt(2);
}
}
如果您使用nested classes (一个类位于另一个类中,具有隐含的父子关系),使用:
OuterClass.this.setThisInt(5);
等等。
关于java - 从被调用的对象调用对象中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17537834/