인터페이스

쪼개발자·2024년 6월 21일

인터페이스란?

  • 추상 메서드의 집합
  • 구현된 것이 전혀없는 설계도. 껍데기(모든 멤버가 public)
interface PlayingCard {
	public static final int SPADE = 4;
    final int DIAMOND = 3; // public static final
    static int HEART = 2; // public static final
    int CLOVER = 1; // public static final
    
    public abstract String getCardNumber();
    String getCardKind();  
    // public abstract String getCardKind();
    // public abstract를 생략한것
}
  • 인터페이스의 조상은 인터페이스만 가능(object아님)
  • 다중 상속이 가능 (추상메서드는 충돌해도 문제없음)
interface Fightable extends Movable, Attackable {}

interface Movable {
	void main(int x, int y);
}

interface Attackable {
	void attack(iUnit u);
}

인터페이스의 구현

  • 인터페이스에 정의된 추상 메서드를 완성하는 것
  • implements 키워드 사용
  • 일부만 구현하는 경우 클래스 앞에 abstract 붙여야함 (추상클래스와 동일)
class 클래스이름 implements 인터페이스 이름 {
}

인터페이스 다형성

interface Fighteable {
  void move(int x, int y);
  void attack(Fightable f);
}


class Fighter extends Unit implements Fightable {
  public void move(int x, int y) { ... }
  public void attack(Fightable f) { ... }
}

// 부모 = new 자식
Unit u = new Fighter();
Fightable f = new Fighter();

f.move(100, 200);
f.attack(new Fighter());

0개의 댓글