자바의 정석 - 인터페이스와 다형성

송용준·2023년 3월 27일

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

  • 인터페이스 구현 클래스의 부모
  • 인터페이스 타입 매개변수는 인터페이스 구현한 클래스의 객체만 가능
class Fighter extends Unit implements Fightable {
	public void move(int x, int y) { } 
    public void attack(Fightalbe f) { } 
    
    Unit u 		= new Fighter();
    Fightable f = new Fighter();
    
    f.move(100,200);
    f.attack(new Fighter());
    
    interface Fightable {
    	void move(int x, int y);
        void attack(Fightable f);	// Fightable 인터페이스를 구현한 클래스의 인스턴스만 가능
    }
    
}

Unit, Fightable 두 곳에서 상속받음 --> 문제 : 충돌(어떤걸 물려받을지 알 수 없으나 인터페이스는 몸통이 없으므로 Unit거 물려받으면 된다.)

u는 Fighter를 사용할 수 있으나 move와 attack만 사용가능

  • 인터페이스를 메서드의 리턴타입으로 지정할 수 있다.
Fightable method() {	// Fightable인터페이스를 구현한 클래스의 인스턴스를 반환
	Fighter f = new Fighter();
    return f;	// 두 문장 합치면 return new Fighter();
}

반환타입(Fightable)이 인터페이스라면 인터페이스를 구현한 객체(f)를 반환해야 함. f(Fighter)는 Fightable로 형변환 가능하므로 사용 가능. Fightable이 조상이므로. (Fightable)이 생략되어있음

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

interface Fightable{	// 인터페이스의 모든 메서드는 public abstract. 예외없이
	void move (int x, int y);	// public abstract가 생략
	void attack(Fightable f);	// public abstract가 생략
}

class Fighter extends Unit2 implements Fightable{
	// 오버라이딩 규칙 : 조상(public)보다 접근 제어자가 좁으면 안된다.
	public void move (int x, int y) {	
		System.out.println("[" + x + "," + y + "] 로 이동");
	}
	public void attack(Fightable f) {
		System.out.println(f + "를 공격");
	}
	
	// 싸울 수 있는 상대를 불러온다.
	Fightable getFightable(){
		Fightable f = (Fightable)new Fighter();	// Fighter를 생성해서 반환
		return (Fightable)f;		// (Fightable) 생략가능
	}
}

public class FighterTest {
	public static void main(String[] args) {
		Fighter f = new Fighter();
		Fightable f2 = f.getFightable();
		f.getFightable();
		Unit2 u = new Fighter();
//		Fightable f = new Fighter();
		u.move(100, 200);
//		u.attack(new Fighter()); 	// Unit2에는 attack()이 없어서 호출 불가
		u.stop();
		
		f.move(100, 200);
		f.attack(new Fighter());
//		f.stop();		// Fightable에는 stop()이 없어서 호출 불가
	}
}
profile
용용

0개의 댓글