Search code examples
javaobjectmethodsscope

How to change the value of an instance variable of an object that didn't call the method?


I'm writing a program in java in which I'd like to change the value of an instance variable of an object inside a method, while that object hasn't called the method. I'm trying to do something similar to the attached code. I'd like to change object2.num inside the method myMethod, but that will give an error, as object2 is outside the scope of myMethod.

public class Main {

  public static void main(String[] args) {

    Item object1 = new Item(2);
    Item object2 = new Item(4);
    
    object1.myMethod();
    System.out.println(object1.num + " " + object2.num);
  }
}

class Item {
  
  int num;

  Item(int n) {
    num = n;
  }

  public int myMethod() {
    object2.num *= this.num;
    this.num *= object2.num;
  }
}

The only solution I've come up with is to give object1 an additional instance variable, num2, which will act as object2.num. Outside of the method, I will then change object2.num to object1.num2. However, this seems very suboptimal and will get annoying when working with multiple variables to change. Is there any more efficient way to achieve this?

I'm still pretty new to coding and there might already be a solution to this, so any help or a link to a solution will be greatly appreciated.


Solution

  • "... I'd like to change the value of an instance variable of an object inside a method, while that object hasn't called the method ..."

    Technically you can, if the object's variable is static.
    Although, this does not appear to be logical for your current design.

    "... I'd like to change object2.num inside the method myMethod, but that will give an error, as object2 is outside the scope of myMethod. ..."

    Correct, in Java, you won't be able to change an object's variable without the actual object.

    "... The only solution I've come up with is to give object1 an additional instance variable, num2, which will act as object2.num. Outside of the method, I will then change object2.num to object1.num2. ..."

    You'll have to provide more details about the functional purpose of the task.

    I recommend passing object2 as a parameter to myMethod.
    Additionally, I had to add a return here, since the method returns an int.

    public int myMethod(Item object2) {
        object2.num *= this.num;
        return this.num *= object2.num;
    }
    

    Or, you could just declare the method with a void return type.

    public void myMethod(Item object2) {
        object2.num *= this.num;
        this.num *= object2.num;
    }
    

    And then, supply object2 as the argument.

    object1.myMethod(object2);
    

    Output

    16 8