티스토리 뷰

1. 캡슐화

💡 유지보수성 증가(낮은 결합도)를 위해 필드의 직접 접근을 제한하고, public 메소드를 이용하여 간접적으로(우회해서) 접근하여 사용할 수 있도록 클래스를 작성하는 기법.
클래스를 작성할 시 특별한 목적이 아닌 이상 캡슐화가 기본적인 원칙으로 사용되고 있다.

 

1-1. 필드에 직접 접근 시 발생할 수 있는 문제점

1-1-1. 필드에 올바르지 않는 값이 들어가도 통제가 불가능하다.

package com.ohgiraffers.section02.encapsulation.problem1;

public class Application {
    public static void main(String[] args) {

        /* 수업목표. 필드에 직접 접근하는 경우 발생할 수 있는 문제점을 이해할 수 있다. */

        /* 설명. monster1 생성 */
        Monster monster1 = new Monster();       // 객체 생성
        monster1.name = "드라큘라";               // 참조연산자(.)를 통해 접근해서 값 대입
        monster1.hp = 200;

        System.out.println("monster1의 이름: " + monster1.name);   // 참조연산자(.)를 통해 값 추출
        System.out.println("monster1의 체력: " + monster1.hp);

        /* 설명. monster2 생성(음수 데이터(원치 않는)로 인한 문제 발생) */
        Monster monster2 = new Monster();
        monster2.name = "프랑켄";
        monster2.hp = -200;

        System.out.println("monster2의 이름: " + monster2.name);
        System.out.println("monster2의 체력: " + monster2.hp);

        /* 설명. monster3 생성 */
        Monster monster3 = new Monster();
        monster3.name = "미라";

        /* 설명. 이 때는 setHp 메소드 내부의 this == monster3 */
        monster3.setHp(-200);   // 값이 들어가지 않음
        monster3.setHp(100);
        monster3.setHp(-150);

        System.out.println("monster3의 이름: " + monster3.name);
        System.out.println("monster3의 체력: " + monster3.hp);


    }
}
package com.ohgiraffers.section02.encapsulation.problem1;

public class Monster {
    String name;
    int hp;

    public void setHp(int hp) {
        if (hp > 0) {
            this.hp = hp;       // 이 메소드를 호출한 객체(Monster 객체) / 이해해야한다!!
        }

        else if(hp <= 0) this.hp = 0;
    }
}

1-1-2. 필드의 이름이나 자료형을 변경할 때 사용하는 쪽에도 수정 영향을 미친다.

package com.ohgiraffers.section02.encapsulation.problem2;

public class Application {
    public static void main(String[] args) {

        /* 수업목표. 필드값 수정 시 발생할 수 있는 문제점을 이해할 수 있다. */
        Monster monster1 = new Monster();
//        monster1.name = "드라큘라";
//        monster1.hp = 200;
//
//        System.out.println("monster1 name = " + monster1.name);
//        System.out.println("monster1 hp = " + monster1.hp);

        monster1.setInfo1("프랑켄 슈타인");
        monster1.setInfo2(200);

        /* 설명. 하지만 여전히 직접 접근은 가능한 상태이다. */
        System.out.println(monster1.kinds);
    }
}
package com.ohgiraffers.section02.encapsulation.problem2;

public class Monster {
//    String name;
//    int hp;

    /* 설명. 메소드를 추가함으로 인해 필드(클래스에 바로 있는 변수)가 수정되어도 이 클래스 내에섬나 에러가 발생함(단일책임의 원칙) */
    String kinds;       // 수정하면 밑에 부분만 영향 간다! 유지보수하기 쉽겠네!
    int mp;

    public void setInfo1(String info1) {
        this.kinds = info1;
    }

    public void setInfo2(int info2) {
        this.mp = info2;
    }
}

1-2. 캡슐화를 적용하여 문제점 해결

package com.ohgiraffers.section02.encapsulation.resolved;

public class Application {
    public static void main(String[] args) {

        /* 수업목표. 접근제어자와 캡슐화에 대해 이해하고 직접 필드 접근을 막는 이유를 이해할 수 있다. */
        Monster monster = new Monster();
//        monster.name = "드라큘라";
//        monster.hp = 1000;

        /* 설명. 필드에 직접 접근이 안되므로 메소드를 통해 우회해서 활용한다. */
        monster.setInfo1("드라큘라");
        monster.setInfo2(1000);

        /* 필기. 정보은닉(information hiding)
        *   1. 구현 은닉
        *   2. 타입 은닉
        *   3. 필드 은닉 -> 캡슐화
        * */

        /* 필기.
        *   캡슐화(Encapsulation)란?
        *    캡슐화는 유지보수를 증가시키기 위해 필드의 직접 접근을 제한하고
        *    public 메소드를 이용해서 간접적으로(우회해서) 접근하여 사용할 수 있도록 만든 기술이다.
        *    클래스 작성 시 특별한 목적이 있지 않다면 캡슐화를 적용하는 것을 기본 원칙으로 하고 있다.
        * */
    }
}
package com.ohgiraffers.section02.encapsulation.resolved;

public class Monster {
    private String name;        // private : 접근 제어자 / 같은 클래스에서만 사용 가능
    private int hp;

    public void setInfo1(String info1) {
        this.name = info1;
    }

    public void setInfo2(int info2) {
        this.hp = info2;
    }
}

'한화시스템 > 백엔드' 카테고리의 다른 글

[BE] JAVA_클래스와 객체_생성자  (0) 2024.07.16
[BE] JAVA_클래스와 객체_추상화  (0) 2024.07.16
[BE] JAVA_클래스와 객체  (0) 2024.07.15
[BE] JAVA_배열  (0) 2024.07.15
[BE] JAVA_분기문  (0) 2024.07.13
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함