0

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;
}

}
3
  • 1
    Which x is which when you do x=x? Commented Feb 24, 2018 at 20:55
  • 3
    x=x? this.x = x; Commented Feb 24, 2018 at 20:56
  • Sorry for not clearing up but its; this.x = x; Commented Dec 24, 2018 at 17:15

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I get the error "Second cannot be resolved to a variable" if I change x=x; to Second.x = x;
@user3396971 Second should be the name of the class.. If you have provided example code and the name of the class is something else then use it instead of Second.
@user3396971 I see that in the code the name of your class is second. By java's naming conventions classes' names should always begin with a capital letter.
Thanks! I've realised what I was doing wrong. Your answer helped greatly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.