I have the following class:
public final class MyClass {
private final int[] arr;
private final String str;
private final int i;
public MyClass(int[] arr) {
this.arr = arr;
this.str = "abc";
this.i = arr.length;
}
public String getStr() {
return str;
}
public int func(int j) {
int res = this.i + j;
return res;
}
}
Is this class immutable? An object is considered immutable if its state cannot change after it is constructed. In this case, all of the fields are private final, so they obviously cannot change (i.e. being reassigned) after an object is constructed. However, I could code something like this:
int[] arr = {1, 2, 3};
MyClass myClass = new MyClass(arr);
// 1
myClass.arr[0] = 100;
System.out.println(Arrays.toString(myClass.arr)); // {100, 2, 3}
// 2
myClass = new MyClass(new int[] {100, 200, 300});
System.out.println(Arrays.toString(myClass.arr)); // {100, 200, 300}
Are 1 and/or 2 considered a change of state? This question appeared on my test, and my answer was that this class is indeed immutable. The correct answer was that the constructor needs to be changed in order for this class to be immutable. An answer which I don't quite understand. Any help would be appreciated