스크린샷 2025-08-08 오전 10.44.51.png

package com.haenin.section02.encapsulation.problem1;

public class Application {

    public static void main(String[] args) {
        /* 목표, 필드에 직접 접근하는 경우 발생하는 문제점을 이해할 수 있다. */
        /* 목표, 필드 = 클래스안에 속성을 말함  */
        Monster monster1 = new Monster();
        monster1.name = "드라큘라";
        monster1.hp = 200;
        monster1.setHp(200);

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

        Monster monster2 = new Monster();
        monster2.name = "프랑켄";
//        monster2.hp = -300;
        monster2.setHp(-300);

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

package com.haenin.section02.encapsulation.problem1;

public class Monster {
    String name;
    int hp;

    /* 설명.
    *   this의 의미
    *   1. 변수명이 동일할 시 지역변수가 우선적으로 인지되는 것을 방지하기 위해
    *       this 명시적으로 작성(만약 이름이 다른 변수들이면 this 생략 가능)
    *   2. non-static 메소드를 호출하는 해당 클래스 타입의 객체로 해석
    *
    * */
    public void setHp(int hp){
        if(hp >= 0 ){
            // 필기. hp = hp; 왼쪽 hp를 매개변수를 먼저 탐색해 가까운위치부터 멀리 찾아나감
            this.hp = hp;
        }else {
            this.hp = 0;
        }

    }
}

package com.haenin.section02.encapsulation.problem2;

public class Application {
    public static void main(String[] args) {
        Monster m = new Monster();
        m.name = " 드라큘라 ";
//        m.hp=200;
        m.setInfo2(200); // 필기. 중계 역할을 인터페이스라 하고 결합도를 낮춘다
    }

}

package com.haenin.section02.encapsulation.problem2;

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

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

package com.haenin.section02.encapsulation.resolved;

public class Application {
    public static void main(String[] args) {
        Monster m = new Monster();
        // 필기. private 자신의 클래스 안에서만 접근 가능
//        m.name ="드라큘라";
//        m.hp = 1000;
        m.setInfo1("뿌꾸");
        m.setInfo2(100);
        System.out.println(m.getInfo());
        /* 설명.
        *   캡슐화(Encapsulation)란?
        *    캡슐화는 유지보수성을 증가시키기 위해 필드(클래스의 속성)의 직접 접근을 제한하고
        *    pulic 메소드를 이용해서 간접적으로(우회해서) 접근하여 사용할 수 있도록 만든 기술이다.
        *    클래스 작성 시 특별한 목적이 있지 않다면 모든 필드에 대해 캡슐화를 작용하는 것을
        *    원칙으로 하고 있다.
        *  */

    }
}

package com.haenin.section02.encapsulation.resolved;

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

    public void setInfo1(String info1){
        this.name = info1;
    }
    public void setInfo2(int info2) {
        if (info2 >= 0){
            this.hp = info2;
        }else {
            this.hp = 0;
        }
    }
    public String getInfo(){
        return name + "의 hp는 " + hp;
    }
}