class Point{
public double x;
public double y;
}
api를 수정하지 않고는 내부 표현을 바꿀 수 없음
(현재 API를 사용하는 외부 코드가 Point
의 필드에 직접 접근하고 있기 때문에 문제가 생길 수 있음)
불변식을 보장할 수 없음
외부에서 필드에 접근할 때 부수 작업을 수행할 수 없음 (필드에 직접 접근하게 되므로)
public class Point {
public double x;
public double y;
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(final double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(final double y) {
this.y = y;
}
}
public 클래스에서 필드를 private으로 바꾸고 public 접근자를 추가하자
getter / setter 로 내부표현 변경이 가능
클라이언트는 public 메서드를 통해서만 데이터 접근이 가능
→ 부수 작업 수행 가능해짐
public class ColorPoint {
private static class Point{
public double x;
public double y;
}
public Point getPoint(){
Point point = new Point();
point.x = 1.2;
point.y = 5.3;
return point;
}
}