Jared Drake
Jared Drake

Reputation: 1002

Separate objects sharing a duplicate method

I know this is probably something very stupid that I am looking over, but I've spent several hours hunting this little problem.

Basically, I have 2 objects that use the same ArrowControl class:

public class ArrowControl extends BoundaryBox{
    private static float value = 0;

    public ArrowControl() {}

    public float getValue() {
        return value;
    }

    public void setValue(float newValue) {
        value = newValue;
    }
}

However, when I use them in another class like this:

public Panel(Context context, AttributeSet attrs) {
    ArrowControl upControl = new ArrowControl();
    ArrowControl downControl = new ArrowControl();
    upControl.setValue(1);
    //upControl.getValue() == 1
    downControl.setValue(2);
    //upControl.getValue() == 2
}

Whenever, I log upControl.getValue() after it is set it equals 1. Then when I log it again after downControl is set, upControl.getValue() equals whatever downControl.getValue() equals.

Does anybody know why or how to fix this problem?

Upvotes: 0

Views: 31

Answers (2)

user2243085
user2243085

Reputation: 43

It looks like it is because the variable is static. This means the same one is used in all instances of ArrowControl

Make it an instance variable and this should go away. (Remove "static")

Upvotes: 3

peter.petrov
peter.petrov

Reputation: 39477

Because you've defined it as static.

private static float value = 0;

So the two instances share it.

Upvotes: 3

Related Questions