Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Object immutable when passed as parameter

Tags:

java

Can I make an Object immutable when passed as a parameter, so that the called method can't change it but the callee can?

So I have somthing like this:

Class Car {
  Wheel wheel_1;

  Axis axis = new Axis(wheel_1);
}


Class Wheel {
  int size;

  setSize(int size) {}
  int getSize() {}      
}

Now I construct a car with a wheel. Then from class car I want to construct an axis.

For that I pass wheel_1 to the constructor of Axis.

Now my question: Can I asure somehow that the constructor of Axis doesnt change the size of wheel_1 but class car can change it.

like image 768
eclipse Avatar asked Apr 19 '13 09:04

eclipse


3 Answers

Yes. Typically this is done by utilising a copy-constructor for the Wheel class.

For example:

wheel_1 = new Wheel(wheel);

Bear in mind, the Wheel class will need to be written in a way that supports this. That is, it should either offer a copy-constructor.

Note: this hasn't made the object immutable. It has merely produced a copy that can't be edited by anything outside your class.

If you return the Wheel instance from any of your other methods, be sure to defensively copy it on the way out too:

Wheel getWheel() {
  return new Wheel(wheel_1);
}

Finally, it's worth mentioning that it's always a good idea to create immutable classes whenever you can. So perhaps you can avoid this issue by actually making Wheel immutable?

like image 180
Duncan Jones Avatar answered Sep 26 '22 00:09

Duncan Jones


Make the Wheel class immutable. Then let the Car object create a new Wheel object when it needs a new size.

public final class Wheel {
    private final int size;

    public Wheel(int size) {
        this.size = size;
    }

    public int getSize() {
        return size;
    }
}

Now you can pass the wheel object to the Axis without any problems.

public class Car {
    private Wheel wheel;
    private Axis axis;

    public Car(int initialWheelSize) {
        wheel = new Wheel(initialWheelSize);
        axis = new Axis(wheel);
    }
}
like image 36
maba Avatar answered Sep 24 '22 00:09

maba


Pass the Axis constructor a copy of wheel_1.

class Car {
    Wheel wheel_1;

    Axis axis = new Axis(new Wheel(wheel_1));
}

Also, Wheel will need a constructor which takes another Wheel object and copies its properties.

like image 27
Gabriel Negut Avatar answered Sep 25 '22 00:09

Gabriel Negut