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 } }
public methods accessandPassing an object as argument to a method.