객체의 상태(멤버 변수)는 외부에서 직접 수정하지 않고, 오직 행위(메서드)를 통해서만 변경해야 함
getter와 setter
setter : 외부 값을 검증하여 데이터의 오염을 방지하는 역할
getter: 객체의 데이터를 안전하게 읽어오는 방법
getter, setter 코드 실습
-클래스 설계(Warrior)
package ch10;
public class Warrior {
private String name;
private int level;
private int hp;
public Warrior(String name) {
this.name = name;
this.level = 1;
this.hp = 100;
}
//레벨 업
public void levelUp() {
this.level++;
this.hp += 50;
System.out.println(name + "민이 레벨 업!" + " 현재 레벨 " + level + " HP " + hp);
}
//체력 변경
//잘못된 수정을 막는 Setter 메서드 만들기 ( 검증 로직)
//멤버 변수에 상태를 단순히 변경할 때 setXX 메서드로 이름을 설계한다.
public void setHp(int hp) {
//체력은 0보다 작을 수 없고, 현재 레벨에서 가질 수 있는 최대치를 넘을 수 없음
//1 --> 100
//2 --> 200
//3 --> 300
int maxHp = level * 100;
if (hp < 0 || hp > maxHp) {
System.out.println("경고 비정상적인 체력 수정 시도 [" + hp + "] 수치를 거부합니다");
return;
}
this.hp = hp;
}
//setter 메서드라 부를 수 있다
public void setName(String name) {
//name.length() --> "홍길동" --> 글자 수를 반환
if (name.length() <= 3) {
System.out.println("캐릭터의 이름은 3글자 이상이어야 합니다");
return;
}
this.name = name;
}
//getter 메서드를 알아보자 : 현재 상태를 안전하게 전달
public int getHp() {
return this.hp;
}
public int getLevel() {
return this.level;
}
}
-실행( GameMain)
package ch10;
public class GameMain {
public static void main(String[] args) {
Warrior warrior1 = new Warrior("최강전사");
//시나리오 1: 정상적인 게임 플레이 (메서드를 통한 상태 변경)
System.out.println("---- 정상 플레이 ----");
warrior1.levelUp();//레벨 2 , 체력 150
//시나리오 2: 악의적인 데이터 수정 시도
//warrior1.hp = 9999; // private - 접근불가
warrior1.setHp(200);
System.out.println(warrior1.getHp());
System.out.println(warrior1.getLevel());
}//end of main
}//end of class