有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    传入对对象的引用

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

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

    OuterClass.this.setThisInt(5);
    

    等等