Here’s my Code
Class A
public class A {
private int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
Class Change
public class Change {
public void changeSomething(A a){
a.setA(13);
}
}
Class Learn
public class Learn {
public static void main(String[] args) {
A a = new A();
Change change = new Change();
change.changeSomething(a);
System.out.println(a.getA());
}
}
The output is 13. Now when i am passing an object to the changeSomething method, internally the value of Object A has been changed but why do i see this effect outside that function?
Is not this equivalent to passing by value in C where unless you return that variable/Object you dont get the updated value.
i.e. dont i need to do a=changeSomething(a); and set the return type of this method to be as A?
Thanks
You’re passing a reference to the original object around. When you write a method
paramis a reference to the original object. The original object isn’t being copied. Consequently when you change this object, the change is visible wherever that object is observed.When you write:
it’s important to realise that the variable is a reference to object type
A, not an actual object typeA. It’s a fine distinction, granted.The above behaviour can cause unexpected effects across your system, and it’s an argument for immutability, especially in threaded environments where changes can be triggered from multiple threads.