Objects do not change their values because, well, your code does not change the object's values. It swaps references, which have been copied into parameters x
and y
, which are local to your change
method.
If you would like to make the objects swap their values, give them a method to get and set whatever value(s) that they may be representing. The code would look like this:
void change (MyClass x,y) {
MyClass temporary= new MyClass();
temporary.copyFrom(x);
x.copyFrom(y);
y.copyTo(temporary);
}
copyTo
is your added method that performs the copying of the internal state of MyClass
. Here is a small example:
class MyClass {
private String firstName;
private String lastName;
public MyClass(String first, String last) {
firstName = first;
lastName = last;
}
public void CopyFrom(MyClass other) {
firstName = other.firstName;
lastName = other.lastName;
}
}