Java

72. 인터페이스의 선언, 상속, 구현 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2024. 12. 23. 13:48

1. 인터페이스(interface)

  • 추상 메서드의 집합
  • 구현된 것이 전혀 없는 설계도(모든 멤버가 public)
interface 인터페이스이름 {
    public static final 타입 상수이름 = 값;
    public abstract 메서드이름(매개변수목록);
}

interface PlayingCard {
    public static final int SPADE = 4;
    final int DIAMOND = 3;	// public static final int DIAMOND = 3; 생략가능
    static int HEART = 2;	// public static final int HEART = 2; 생략가능
    int CLOVER = 1;		// public static final int CLOVER = 1; 생략가능
    
    public abstract String getCardNumber();
    String getCardKind();	// public abstract String getCardKind(); 생략가능
}

 

2. 인터페이스의 상속

  • 인터페이스의 조상은 인터페이스만 가능(Object가 최고 조상 아님)
  • 다중 상속이 가능(추상메서드는 충돌해도 문제 없음)
interface Fightable extends Movable, Attackable { }

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

interface Attackable {
    void attack(Unit u);
}

 

3. 인터페이스의 구현

  • 인터페이스에 정의된 추상 메서드를 완성하는 것
class 클래스이름 implements 인터페이스이름 {
    // 인터페이스에 정의된 추상메서드를 모두 구현해야 한다.
}

interface Fightable {
    void move(int x, int y);
    void attack(Unit u);
}

class Fighter implements Fightable {
    public void move(int x, int y) { /* 내용 생략 */ }
    public void attack(Unit u)	{ /* 내용 생략 */ }
}
  • 일부만 구현하는 경우, 클래스 앞에 abstract를 붙여야 함
abstract class Fighter implements Fightable {
    public void move(inx x, int y) { /* 내용 생략 */ }
}