본문 바로가기
Java/기본 개념 및 클래스

[Java] 57. 인터페이스 활용: 스타크래프트 소스 코드 수정하기

글: Song hyun 2024. 4. 26.
728x90
반응형

[Java] 57. 인터페이스 활용: 스타크래프트 소스 코드 수정하기

함께 보면 좋을 글:

(1) Java로 스타크래프트 모델링하기 (객체 지향 패러다임 응용)

https://whatsthatsound.tistory.com/61

(2) Java로 스타크래프트 모델링하기 (상속, 메서드 오버로딩 개념 응용)

https://whatsthatsound.tistory.com/86

(3) Java로 스타크래프트 모델링하기 (다형성 활용)

https://whatsthatsound.tistory.com/90

 

*다형성이란?

https://whatsthatsound.tistory.com/89

 

*인터페이스와 추상 클래스의 활용

https://whatsthatsound.tistory.com/108


(1) 인터페이스는 기능적인 요소들에 강제성을 부여하는 데에 쓰인다.

Unit 내의 질럿, 마린, 저글링이 공통적으로 지니는 메서드는 attack/beAttacked 메서드이다.

해당 메서드들을 인터페이스에 구현하면, 해당 인터페이스를 implements받는 클래스들은

필수적으로 attack/beAttacked 메서드를 오버라이드하게 된다.

 

(2) unit 클래스는 질럿, 마린, 저글링이 공통적으로 지니는 멤버변수, 메서드들을 담아둔 클래스이다.

하지만 질럿, 마린, 저글링에게도 세부적인 차이(hp, power, 공격시 스크립트 등)들은 존재하며,

이를 오버라이딩(재정의)해야 할 필요가 있다.

->따라서 unit을 가상 클래스(abstract class)로 만들면 이러한 메서드들을 재정의하도록 강제성을 부여할 수 있다!

package starcraft.ver05;

public interface Attacker {
	
	// 공격 메서드 설계
	public void attack();

}
package starcraft.ver05;

public interface Defender {
	
	// 방어 메서드 설계
	public void beAttacked();

}
package starcraft.ver05;
/**
 * 접근 제어 지시자
 * public
 * protected
 * default
 * private
 */
public abstract class Unit implements Attacker, Defender, Showing {
	
	protected String name;
	protected int power;
	protected int hp;

	public Unit(String name) {
		this.name=name;
	}

	public String getName() {
		return name;
	}

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

	public int getPower() {
		return power;
	}

	public void setPower(int power) {
		this.power = power;
	}

	public int getHp() {
		return hp;
	}

	public void setHp(int hp) {
		this.hp = hp;
	}
	
	public void showInfo() {
		System.out.println("=====상태창=====");
		System.out.println(" 이름: "+this.name);
		System.out.println(" 공격력: "+this.power);
		System.out.println(" 생명력: "+this.hp);
	}
	
	public void beAttacked(int power) {
		if (hp <= 0) {
			System.out.println("[" + this.name + "]은 이미 사망했습니다.");
			hp = 0;
			return;
		}
		hp -= power;
	}
	
	public void attack(Unit u) {
		System.out.println("[" + this.name + "]가 "+u.name+"를 공격합니다.");
		beAttacked(this.power);}
}
728x90
반응형