Aymen Bou
Aymen Bou

Reputation: 1109

How to change an objects values through methods in a different class Java

So I'm trying to edit an object's x value from a method in a different class. The real reason I'm doing this is far more complicated but I just wanted to simplify things.

I am creating a game and I want the object that belongs to the first Class to be updated throughout the game. However when I try to update it, it appears in the other class however as soon as scope is returned to the first class the x value remains 0.

I have been struggling with this for hours...

public class first {
    private second Second;

    public void view() {
        System.out.println(this.Second.x);
    }
    public void newObj() {
        Second = new second();
    }

    public void changeObj() {
        Second.changeX(4);
        Second = Second.getSecond();
    }

   public static void main(String[] args) {
    // TODO Auto-generated method stub
    first First = new first();
    First.newObj();
    First.changeObj();
    First.view();
   }

}


public class second {

public static int x=0;

public second getSecond() {
    return this;
}

public second(){
    x=0;
}

public static void changeX(int x) {
    x = x;
    System.out.println(x);
}

public int getX() {
    return x;
}

}

Upvotes: 0

Views: 3440

Answers (1)

Valentin V.
Valentin V.

Reputation: 109

You're encountering this because of the way the assignment is done:

x=x;

Just doing this should trigger a warning message "The assignment to variable x has no effect". This is because you're not referring to the static variable x but the argument itself.

Each non-static variable exists in the context of an object. In this case x is static so the usage of this.x = x; in a static context is not possible either. The correct approach is

Second.x = x;

Upvotes: 5

Related Questions