본문 바로가기

자바/정리

(JAVA)캡슐화 (접근제어자)

우리가 식당에서 밥을 주문한다고 상상해 보자.

 

우리는 자리에 앉은뒤에 서버에게 원하는 메뉴를 고르고 서버는 주방에 알린뒤 음식을 가지고 나올것이다.

 

당연하지만 생각해보면 주방에서 음식을 줄때 식당의 비법이 담긴 레시피를 손님들에게 공개하며 음식을 주지는 않을것이다.

 

프로그램도 마찬가지 이다. 우리가 네이버에 로그인을 할때 우리의 데이터 베이스를 우리가 직접 찾아서 아이디와 비밀번호의 일치 여부를 확인하지 않을 것이다.

 

 

이렇게 프로그램이 실제 구연하는 내용을 은닉 하는 행위를 캡슐로 감싼것에 비유하여 캡슐화 라고 한다.

 

이번 포스트 에서는 객체지향에서 중요한 개념인 캡슐화를 이해하는 시간을 가져볼 것이다.

 

캡슐 하면 어떤 이미지가 떠오르는가?

이런 이미지가 떠오를 것이다.

 

캡슐화를 하여 분리는 하는 이유는 크게 두가지가 있다.

 

1.정보를 보호하기 위해서.

2.내부적으로만 사용하는 정보를 쉽게 알기 위해서 (유지보수에 좋겠죠?)

 

먼저 이 두가지 이유를 자세히 이해하기 위해서는 우리는 접근제어자 getter setter 메서드를 알아야한다.

 

------------------------------------------------------------------------------------------

접근제어자는 클래스 혹은 메서드나 변수가 영향을 미칠수 있는 범위를 제안하는 기능을 수행하는것들이다.

 

범위를 주기 위해서 쓰이는 것은 다음과 같다.

(순서대로 봤을때 private이 제일 범위가 작음)

public >protected>default>private

 

 

이렇게 보면 이해가 안갈것이다. 코드를 살펴보자. (혹시 어려우면 바로 설명으로 가자)

 

처음 패키지 (여기를 주로 사용할꺼임)

package firstpack;

import secondpack.other;


class first{
    public void call(){
        this.everyone();
        this.sheildup();
        this.nomal();
        this.catchmeifyoucan();
    }
    public void everyone(){
        System.out.println("누구나 볼수 있어요.");
    }
    protected void sheildup(){
        System.out.println("가드올려");
    }
    void nomal(){
        System.out.println("나는 기본");
    }
    private void catchmeifyoucan(){
        System.out.println("어림도 없지.");
    }
}
class second{

    public void youaremine(){
        first c2 = new first();
        c2.everyone();
        c2.sheildup();
        c2.nomal();
        //c2.catchmeifyoucan()
    }

    public void othersaremine(){
        other c3 = new other();
        c3.otherpublic();
        //c3.otherprotected();
        //c3.othernomal();
        //c3.otherprivate();
    }
}
class third extends other{

    public third(){

        this.otherpublic();
        this.otherprotected();
        //this.othernomal();
        //this.otherprivate();

    }
}
    public class Access {

        public static void main(String[] args) {

            first c1 = new first();
            c1.everyone();
            c1.sheildup();
            c1.nomal();
            //c1.catchmeifyoucan();

            c1.call();
        }
    }

 

두번째 패키지

 

package secondpack;

public class other {

  //public other(){}
        public void otherpublic(){
            System.out.println("다른 공개");
        }
        protected void otherprotected(){
            System.out.println("다른 보호");
        }
        void othernomal(){
            System.out.println("다른 기본");
        }
        private void otherprivate(){
            System.out.println("다른 비밀");
        }

    public static void main(String[] args) {

    }
}

 

출력은 아래와 같다.

 

누구나 볼수 있어요.
가드올려
나는 기본
누구나 볼수 있어요.
가드올려
나는 기본
어림도 없지.

 

차근차근히 설명하겠다. 표를 한번 봐두면 좋겠다.

이번에는 설명을 위해 패키지를 두개 준비했다. 참고로 주석 처리된것들은 주석이 풀리면 에러뜨는 것들이다.

 

-----------------------------------------------------------------------------------------------------------------------

(위에 내용들이 어려웠다면 스트레스 받지말고 여기부터 봐도 어느정도 괜찮을 것이다.)

 

public protected default private 이들의 사전적 의미는 아무 상관이 없다. protected...? 뭐가 보호 되었나 같은 생각말이다. 접근제어자는 자바를 만든 사람이 정한 정의라서 우리는 범위에만 집중하고 암기한다.

 

또한 코드를 살펴봐도 default 라는 제어자는 안보일텐데 아무것도 안쓰면 그게 default 이다.

 

설명을 4가지로 나눠보았다.

 

*4가지 각 설명들은 public protected default private 를 전부 호출 해볼것이다.

 

1.클래스 내부에서 호출할때

2.클래스 외부에서 호출할때

3.다른 패키지를 상속받고 호출할때

4.상속없이 다른 패키지를 호출할때

 

 

1.클래스 내부에서 호출할때

class first{
    public void call(){
        this.everyone();
        this.sheildup();
        this.nomal();
        this.catchmeifyoucan();
    }
    public void everyone(){
        System.out.println("누구나 볼수 있어요.");
    }
    protected void sheildup(){
        System.out.println("가드올려");
    }
    void nomal(){
        System.out.println("나는 기본");
    }
    private void catchmeifyoucan(){
        System.out.println("어림도 없지.");
    }
}
c1.call();

이부분을 실행 시키면 다음과 같다. (전체 코드에서 잘라온 예시라서 말이 그냥 실행이라는 거다.)

 

누구나 볼수 있어요.
가드올려
나는 기본
어림도 없지.

 

잘보면 public protected default private 접근 제어자들을 사용하여 first 클래스 안에 메서드 들을 만들었다.

 

그런데 이걸 같은 클래스 안에 call 메서드를 만들고 this로 호출 한뒤에 인스턴스화를 시켜보았다. 그리고 c1.call();을 호출하면 접근 제어자의 종류에 관계없이 호출 할수 있는것이 확인이 된다.

 

여기서 알수 있는점은 동일 클래스안에서는 전부 자유롭게 호출이 가능하다는 점이다.

 

 

2.클래스 외부에서 호출할때

 

class second{

    public void youaremine(){
        first c2 = new first();
        c2.everyone();
        c2.sheildup();
        c2.nomal();
        //c2.catchmeifyoucan()
    }

잘보면 private 호출은 주석처리를 한것이 보인다. 그렇다. private은 다른 클래스에서 사용이 불가능 하다. (상속받고 this로 호출해도 마찬가지)

 

 

3.다른 패키지를 상속받고 호출할때

 

class third extends other{

    public void youaremine2(){

        this.otherpublic();
        this.otherprotected();
        //this.othernomal();
        //this.otherprivate();

    }
}

 

*other클래스는 다른 패키지에서 만든 클래스 이다.(위에 참고)

 

상속을 받게 된다면 다른 패키지에 있어도 protected 까지는 호출이 가능하다.

 

 

 

4.상속없이 다른 패키지를 호출할때

 

class second{

    public void othersaremine(){
        other c3 = new other();
        c3.otherpublic();
        //c3.otherprotected();
        //c3.othernomal();
        //c3.otherprivate();
    }

 

상속 받지 않고 인스턴스로 불러오면 public만 사용이 가능하다.

 

 

범위는 이 4가지가 전부이다. 이걸 조합해서 복잡하고 보안성이 있는 프로그램을 만드는 것이다.

 

여기 까지 읽었다면 다시 한번 위로 올라가서 표를 확인해 주면 머리속이 정리가 될것이다.

 

이해하는데 지칠수도 있을것 같다. getter와 setter는 다음 포스트에 이어서 설명하겠다.

'자바 > 정리' 카테고리의 다른 글

(JAVA) 추상화  (0) 2022.11.17
(JAVA)캡슐화 (getter와 setter)  (0) 2022.11.13
(JAVA)객체지향  (0) 2022.11.12
(JAVA)Overriding 과 Overloading  (0) 2022.11.12
(JAVA)상속2  (0) 2022.11.11