user5767743
user5767743

Reputation:

How can one class change another class value without the original class object

Please pardon me, I am trying to understand this concept, don't want to just accept it without knowing what is happening. I read that only object of class X can modify itself, from the code below, Class ModifyX as a matter of fact can change X.x.num by calling it setNum method.

My questions are:

How come [ModifyX object "mx"] is able to change [ X object "x" ] value out of X?

The value of y passed as argument is changed in X, but why is it not changed in main(String[] args)?

public class X {
    private int num;
    public void setNum(int num) {
        this.num = num;
    }

    public void getNum() {
        System.out.println("X is " + num);
    }

    public static void main(String[] arsgs) {
        int y = 10;

        X x = new X();
        x.setNum(y);   //sets the value of num in X to y;
        x.getNum();   // print the value of num in X

        ModifyX mx = new ModifyX();     // A new class that is inteded to modify X
        mx.changeX(x);                 //calls the set method of X with new Value 5
        x.getNum();                // returns the new Value passed in changeX instead of y

        System.out.println("Integer Y is not changed = " + y); // but y still remains the same
    }
}

class ModifyX {
    public void changeX(X num) {
        num.setNum(5); // changes  y to 5
    }
}

Upvotes: 0

Views: 2310

Answers (2)

Buddy Yaussy
Buddy Yaussy

Reputation: 555

So 'num' is a non-public member of class X, so only the class itself is able to modify this directly. However, class X also provides the 'public' accessor function "setNum", which is a method which anyone using the class can use to "indirectly" set the value of the property 'num'.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

This method

s.setNum(y);

takes a copy of the value y and pass it to the method. Java is always pass-by-value so it will always pass a shallow copy of the value. This means you can change either copy of this value without effecting the other.

This method

num.setNum(5);

is the same as

num.num = 5;

so exactly one value is changed here which the the num fields of the X num.

Your local variable y is 10 and this variable isn't changed anywhere so there is no reason believe it should change.

Upvotes: 2

Related Questions