In this Q&A, we'll go over how to make a class immutable.
Object is immutable if its state cannot be modified after its constructed. This can be achieved by
- Making the member variable private and final
- initializing the member variable in the constructor and
- not exposing any setter methods
See the example below
package com.javahowdoi.thread;
public class Immutable {
final private int i;
public Immutable(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
Comments
Post a Comment