Popacha
Popacha

Reputation: 45

Java object references

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?

Upvotes: 2

Views: 51

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

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;
    }
}

Upvotes: 3

Related Questions