Is this a immuable class ?
is it necessary for a immutable class to be final ?
I have a box class that is to be immuable , changes to a box should create a new box .
public class MyImmutableBox {
Integer length;
Integer breadth;
/*Constructor*/
public MyImmutableBox(Integer length,Integer breadth){
this.length=length;
this.breadth=breadth;
}
/*Getters*/
public Integer getBreadth() {
return breadth;
}
public Integer getLength() {
return length;
}
/*Member functions*/
/*Changing entire box size*/
public MyImmutableBox changeMyBoxSize(Integer lengthToBeAltered,Integer breadthToBeAltered){
return new MyImmutableBox(length+lengthToBeAltered,breadth+breadthToBeAltered);
}
/*Changing either length otr breadth*/
public MyImmutableBox changeMyBoxLenth(Integer lengthToBeAltered){
return new MyImmutableBox(length+lengthToBeAltered,breadth);
}
public MyImmutableBox changeMyBoxBreadth(Integer breadthToBeAltered){
return new MyImmutableBox(length,breadth+breadthToBeAltered);
}
}
No, it’s definitely not immutable. Your
lengthandbreadthfields aren’t private or readonly, so this code will work:(It’s not clear why you’re using
Integerrather thanint, by the way.)If you either make the fields private and avoid modifying them within your class, or make them final, or (preferrably) both, then the type as you’ve shown it will be immutable. It won’t prevent mutable subclasses though – you should make the class final at the same time to do that.