본문 바로가기

school of computing/Object-Oriented programming

JAVA | Ch03. Java의 Encapsulation (information hiding)

Information Hiding 

프로그래머는 class method를 사용하여 코드의 상세한 내용을 공개할 필요가 없고 오직 그 method가 무엇을 하는지만 알리면 된다. 그래서 informaiton hiding으로 상세한 내용을 숨기도록 method를 설계한다. 

 

상세한 내용을 숨기려면 어떻게 해야할까?

 

Java에서는 내용을 공개하거나 숨길때 public과 private modifier을 사용한다.

  • public : 다른 class에서 method나 instance variable을 사용하는 것에 제약이 없다.
                class는 일반적으로 public으로 선언된다.
  • private : 다른 class에서 method나 instance variable의 이름을 사용하여 직접 접근할 수 없다.
                  instance variables은 보통 private로 선언된다.  >> class의 다른 유저에게 보이지 않도록 함.
public class Rectangle {
    public int width;
    public int height;
    public int area;

    public void setDimensions(int newWidth, int newHeight){
        width = newWidth;
        height = newHeight;
        area = width * height;
    }

    public int getArea()
    {
        return area;
    }

}

 

위 class를 main에서 아래처럼 실행했을 때, area가 50이지만 이 후에 width를 6을 넣어줌으로써 해당 객체의 area와 width, height값이 맞지 않게 된다.  때문에 instance variable은 직접 접근 할 수 없도록 숨겨 주어야 한다.

Rectangle box = new Rectangle();

box.setDimentions(10,5);

box.width = 6;

System.out.println( box.getArea() );

 

아래 코드는 Rectangle class의 instance variable을 private로 선언하여 직접 접근 할 수 없도록 하였다.

public class Rectangle {
    private int width;
    private int height;
    private int area;

    public void setDimensions(int newWidth, int newHeight){
        width = newWidth;
        height = newHeight;
        area = width * height;
    }

    public int getArea()
    {
        return area;
    }

}

객체의 instance variable에 값을 넣기 위해서는 무조건 setDimensions()를 사용해서만 접근할 수 있다. 

 

위처럼 instance variable에 접근하도록 하기 위해 두 종류의 method를 사용한다.

Accessor methods (a.k.a. getters) : private instance variables의 데이터를 유저가 볼 수 있도록 한다.

Mutator methods(a.k.a. setters) : 유저가 private instnace variables의 데이터를 설정할 수 있도록 한다.

 

instance variable이외에도 method를 private로 설정하는 경우도 있다.

이 경우는 class내부에서만 사용되어서 유저가 그 method를 invoke할 필요가 없는 method를 helper method라고 하고 이를 private로 숨긴다. 

 

>> Encapsulation : class가 무엇을 하는지(interface) 는 노출 하면서, 어떻게 수행하는지(implementation)는 숨긴다.

encapsulation은 class정의를 Class interfaceClass implementation으로 나눈다.

Class interface : public method의 head와 comment를 제공한다. (public, static, final로 선언된 variable)

Class implementation :  public과 private method의 정의를 포함한다. (bodies of public method, private 선언된 것)

 

그럼 class를 Well-Encapsulation하려면 어떻게 해야할까?

  • 모든 instance variables를 private로 선언한다.
  • 객체의 data에 접근 할 수 있도록 public accessor method(getter)와 public mutator methods(setter)를 제공한다.
  • 각 public method heading 앞에 method의 사용방법을 명시하는 commet를 배치한다
  • helping method는 private로 선언한다.
  • class definition내에 class의 implementation을 설명하는 commet를 적는다.

겁나 양 많네.. 진짜로 퀴즈 진짜 ....15분이 말이되냐고 영어 읽는데만 1분 걸릴듯;