인터페이스를 이용한 다형성

essential·2023년 8월 27일

객체 지향

목록 보기
35/40

인터페이스를 이용한 다형성

  • 인터페이스도 구현 클래스의 부모
class Fighter extends Unit implements Fightale {
		public void move (int x, int y) { /* */}
		public void attack (Fightable f) { /* */}
}

Unit u = new Fighter();
Fightable f = new Fighter();

f.move(100, 200);
f.attack(new Fighter());
  • Unit 부모 / Fightable 유사 부모 = 다중 상속
  • 인터페이스 타입 매개 변수는 인터페이스 구현한 클래스의 객체만 가능
  • 인터페이스를 메서드의 러턴 타입으로 지정할 수 있다.

예제

abstact class Unit {
	int x, y;
	abstact void move(int x, int y);
	void stop() { System.out.println("멈춥니다.");}
}

interface Fightable {
	void move (int x, int y); // public abstact가 생략 됨 
	void attack (Fightable f); // public abstact가 생략 됨

class Fighter extends Unit implements Fightable {
		public	void move (int x, int y) { // 오버라이딩 규칙 : 조상 (public) 보다 접근 제어자가 범위가 좁으면 안 된다.
					System.out.println("["+x+",y+"]로 이동");
		}
		public void attack (Fightable f) {
					System.out.println(f+"를 공격");
		}
		
		Fighterble getFighterble() {
				Fighter f = new Fighter(); // Fighter 를 생성해서 반환
				return f;
		
public class FighterTest {
		
	public static void main(String[] args) {
			Fighter f = new Fighter();
			Fightable f2 = f.getFightable();
	}
}
profile
essential

0개의 댓글