String
, Integer
, Long
등이 존재setter method를 제공하지 않는다.
모든 필드를 private, final로 선언한다.
클래스를 final로 선언한다.
객체를 생성하기 위한 생성자/정적 팩토리를 추가한다.
예시
public final class ImmutableClass {
private final int num;
private final int count;
private final List<String> list
public ImmutableClass (int num, int count, List<String> list) {
this.num = num;
this.count = count;
this.list = new ArrayList<>(list);
}
public int getNum() {
return num;
}
public int getCount() {
return count;
}
public List<String> getList() {
return new ArrayList<>(list);
}
}