0

In Java, how do you set variables in a calling object from the object that is being called? I guess I could set up some kind of struct class, but can someone show me if there is a simpler way to do it, such as some modification of the pseudocode below:

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
  • Can you please explain your reasons for doing this? I expect that there are other solution to your original problem that are in line with common Object Oriented programming practices. Commented Jul 9, 2013 at 0:03

1 Answer 1

1

Pass in a reference to the object.

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

If you're using nested classes(one class inside the other with an implied parent-child relationship), use:

OuterClass.this.setThisInt(5);

and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the quick answer. Thank you. Impressive response time.
@CodeMed Yeah, I keep this open in a tab at all times. Really handy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.