Java의 정석

인터페이스(interface)

donghyeob.k 2022. 4. 19. 20:20

인터페이스는 일종의 추상 클래스이다.

인터페이스는 추상 클래스보다 추상화 정도가 높아서 몸통을 갖춘 일반 메서드 또는 멤버 변수를 구성원으로 가질 수 없으며 오직 추상 메서드와 상수만을 멤버로 가질 수 있다.

interface interfaceName {
    public static final {type} {constantName} = value;
    public abstract methodName(params);
}

인터페이스의 멤버들은 다음과 같은 제약사항이 있다.

  • 모든 멤버 변수는 public static final 이어야 하며 이를 생략할 수 있다.
  • 모든 메서드는 public abstract 여야 하며 이를 생략할 수 있다.(static 메서드와 default 메서드는 예외, jdk1.8부터)
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 getCartNumber();
    String getCardKind(); // public abstract String getCardKind();
}

위와 같이 생략된 제어자는 컴파일 시에 컴파일러가 자동적으로 추가해준다.