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.
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?
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);
    }
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With