<aside> 💡 목적 캡슐화의 이점을 잘 살릴 수 있도록 코드를 설계해라 → HOW? public을 최소화하고 클래스의 정보를 외부로 최대한 적게 유출하라 → WHY? public과 같이 외부에 공개된 API들은 변경이 어렵고, 영원히 관리해줘야한다.

</aside>

캡슐화

캡슐화의 이점을 살리지 못할 경우

Dimension class 와 이의 클라이언트인 Component class

public 클래스의 필드를 직접 노출(public field)하지 말라는 규칙을 어긴 사례(Item67)

public class Dimension extends Dimension2D implements java.io.Serializable {
		
		//field값을 public으로 설정 
    public int width;
    public int height;
		 

	  @Transient
		public Dimension getSize() {
	    return new Dimension(width, height);
	    //방어적 복사 
	    //getSize()로 얻은 객체가 원본 Dimension객체의 height, width를 변경할 수
	    //없게 하기 위해서 방어적 복사를 해야한다
		}

}    

public abstract class Component implements ImageObserver, MenuContainer,
                                           Serializable
{

    /**
     * The width of the component.
     *
     * @serial
     * @see #getSize
     */
    int width;

    int height;
    

    public Dimension getSize() {
        return size();
    }

    @Deprecated
    public Dimension size() {
        return new Dimension(width, height);
    }
    
    
    
    /**
     * Returns the current width of this component.
     * This method is preferable to writing
     * {@code component.getBounds().width},
     * or {@code component.getSize().width} because it
     * doesn't cause any heap allocations.
     *
     * @return the current width of this component
     * @since 1.2
     */
    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }
    
}