Ch7-38. 인터페이스 → 다형성
0. 목차
Chapter7. 객체지향 프로그래밍Ⅱ
Ch7 - 38. 인터페이스를 이용한 다형성
Ch7 - 38. 인터페이스를 이용한 다형성
▶ 인터페이스도 다형성 형성이 가능한가?
▷ 가능
▷ 인터페이스도 구현 클래스의 반만 부모
▶ 인터페이스 타입 매개변수
▷ 인터페이스 구현한 클래스의 객체만 가능
▶ 인터페이스 리턴타입
▷ 인터페이스를 메서드의 리턴타입으로 지정 가능
▶ 실습
▷ 추상 클래스 Unit
abstract class Unit {
int x, y;
abstract void move(int x, int y);
void stop() { System.out.println("stop"); }
}
▷ interface Fightable
interface Fightable {
void move(int x, int y);
void attack(Fightable f);
}
▷ 클래스 Fighter : Unint 상속, Fightable 구현
class Fighter extends Unit implements Fightable {
public void move(int x, int y) { // public 안쓰면 에러!
System.out.printf("(%d, %d) 이동\n", x, y);
}
public void attack(Fightable f) { // public 안쓰면 에러!
System.out.println(f + "를 공격");
}
}
- public 미작성 시, 에러나는 이유 : 오버라이딩 규칙 때문
- 오버라이딩 규칙 : 조상 접근제어자 <= 자손 접근제어자
- 조상 : interface Fightable → 모든 메서드가 추상 메서드(public abstract 생략)
interface Fightable { void move(int x, int y); // public abstract 생략 void attack(Fightable f); // public abstract 생략 }
- 자손 : default는 조상 접근제어자 public보다 작음, 그래서 public 생략 불가
public void move(int x, int y) { } public void attack(Fightable f) { }
▷ 클래스 Fighter : 리턴 타입이 Fightable인 getFightable 메서드
Fightable getFightable() { // 리턴 타입 Fightable
Fightable f = new Fighter();
return (Fightable)f; // 리턴 타입 Fightable과 일치시키기 위해 형변환, 자동 형변환 가능
}
▷ 실행
class FighterTest {
public static void main(String[] args) {
Fighter f = new Fighter();
f.move(100, 200);
f.attack(new Fighter()); // Fighter f2 = new Fighter(); → f.attack(f2);
Fightable f2 = f.getFightable(); // getFightable 리턴 타입 Fightable과 일치시켜 호출
}
}
▷ 실행 불가 경우
Fightable f = new Fighter();
Unit u = new Fighter();
f.move(100, 200);
f.attack(new Fighter());
f.stop(); // 실행 불가, Fightable애 stop없음
u.move(100, 200);
u.stop();
u.attack(new Fighter()); // 실행 불가, Unit에 attack없음