![[JAVA] 46. 메서드 오버라이딩](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog%3Ftitle%3D%255BJAVA%255D%252046.%2520%25EB%25A9%2594%25EC%2584%259C%25EB%2593%259C%2520%25EC%2598%25A4%25EB%25B2%2584%25EB%259D%25BC%25EC%259D%25B4%25EB%2594%25A9%26logoUrl%3Dhttps%253A%252F%252Finblog.ai%252Finblog_logo.png%26blogTitle%3Dsxias&w=2048&q=75)
부모의 메서드를 자식이 재정의 하면
- 부모의 메서드를 호출하는 순간 부모의 메서드가 무효화(Method Override)
- 자식의 메서드가 호출 (동적 바인딩)

오버로딩으로 게임 만들기
- 아래 예제를 사용해서 코드를 완성하시오.
문제 분석
- Dark Templar (hp=100, power=70)
- Archon (hp=100, power=70)
- 5가지 유닛이 서로 다 공격할 수 있게 attack() 구현하기
- 생성
- Zealot 2, Dragoon 2, Dark Templar 2, Reever 2, Archon 2
- 공격
- 질럿이 드라군 공격 → hp 확인
- 질럿이 다크템플러 공격 → hp 확인
- 리버가 아칸 공격 → hp 확인
- 아칸 리버 공격 → hp 확인
- 드라군이 다크템플러 공격 → hp 확인
- 리버가 리버 공격 → hp 확인
package ex05.ch03;
class Protoss {
}
class River {
int hp;
int power;
public River() {
this.hp = 100;
this.power = 50;
}
public void attack(River unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Zealot unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Dragoon unit) {
unit.hp = unit.hp - this.power;
}
}
class Dragoon {
int hp;
int power;
public Dragoon() {
this.hp = 100;
this.power = 10;
}
// 기존 오브젝트 수정
public void attack(River unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Zealot unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Dragoon unit) {
unit.hp = unit.hp - this.power;
}
}
class Zealot {
int hp;
int power;
public Zealot() {
this.hp = 100;
this.power = 20;
}
// 기존 오브젝트 수정
public void attack(River unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Dragoon unit) {
unit.hp = unit.hp - this.power;
}
public void attack(Zealot unit) {
unit.hp = unit.hp - this.power;
}
}
public class StarGame {
public static void main(String[] args) {
Zealot z1 = new Zealot();
Zealot z2 = new Zealot();
Dragoon d1 = new Dragoon();
z1.attack(d1);
System.out.println("드라군 d1의 hp : " + d1.hp);
z1.attack(z2);
System.out.println("질럿 z2의 hp : " + z2.hp);
}
}
Share article