Protoss(부모) class에 attack method가 있어야 Override 되면서 동적 바운딩으로 Arkan,DarkTempler,River,Dragoon,Zealot(자식) class의 attack method 호출 가능
class Protoss(부모) method
class Protoss {
public int getHp() {
return 100;
}
public void setHp(int hp) {
}
public void attack() { // Arkan,DarkTempler,River,Dragoon,Zealot(자식) 클래스가 Protoss(부모) 클래스의 무효화로 동적 바운딩 되는 메서드를 호출 ❗
}
}
Debugging 결과
class Protoss {
public int getHp() {
return 100;
}
public void setHp(int hp) {
}
public void attack(Protoss protoss) {
}
}
class Arkan,DarkTempler,River,Dragoon,Zealot(자식) method
class Arkan extends Protoss { // hp: 100, power: 70
int hp;
int power;
public Arkan() {
this.hp = 100;
this.power = 70; // 객체의 초기화 위한 생성자 필요
}
// getter
public int getHp() {
return hp;
}
// setter
public void setHp(int hp) {
this.hp = 100;
this.power = 70; // 1. hp의 변화만 확인하니 power은 필요없음 2. 들어가야 되는 값은 this.hp=100; 이 아닌 this.hp=hp; ! → 변화된 값을 받기 위함, this.hp=100;은 변화를 줄 수 없다
}
public void attack(Arkan a1) { // Protoss(부모)와 타입이 일치해야 무효화를 통한 동적바인딩이 일어나므로 Arkan(자식)이 아닌 Protoss(부모)의 타입이 들어가야함
a1.setHp(a1.getHp() - this.power);
}
}
Debugging 결과
class Arkan extends Protoss {
int hp;
int power;
public Arkan() {
this.hp = 100;
this.power = 70;
}
// getter
public int getHp() {
return hp;
}
// setter
public void setHp(int hp) {
this.hp = hp;
}
public void attack(Protoss a1) {
a1.setHp(a1.getHp() - power);
}
}
생성할 때
public class StarGame {
public static void main(String[] args) {
// 2개씩 생성
// ❗ Protoss(부모)를 통해 자식의 method를 호출해야 하므로 Zealot(자식)이 아닌 Protoss(부모)가 들어가야함 !
Zealot z1 = new Zealot();
Zealot z2 = new Zealot();
Dragoon d1 = new Dragoon();
Dragoon d2 = new Dragoon();
River r1 = new River();
River r2 = new River();
DarkTempler da1 = new DarkTempler();
DarkTempler da2 = new DarkTempler();
Arkan a1 = new Arkan();
Arkan a2 = new Arkan();
// 공격
//→ 질럿이 드라군 공격 hp 확인
z2.attack(d2);
System.out.println(d2.getHp());
Debugging 결과
public class StarGame {
public static void main(String[] args) {
// 2개씩 생성
Protoss z1 = new Zealot();
Protoss z2 = new Zealot();
Protoss d1 = new Dragoon();
Protoss d2 = new Dragoon();
Protoss r1 = new River();
Protoss r2 = new River();
Protoss da1 = new DarkTempler();
Protoss da2 = new DarkTempler();
Protoss a1 = new Arkan();
Protoss a2 = new Arkan();
Share article