2

I have class, and inside it code:

MyClass x= value1;
MyClass y= value2;

void change (MyClass x,y) {
 MyClass temporary= x;
 x=y;
 y=temp;
}

My question is why my objects would not change their values (x and y will point to values before running this method)? And how to make to change them?

1

1 Answer 1

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.