[자바/심화] 인터페이스(interface)

정의

- interface 키워드로 선언된 추상 클래스로써, 추상 메소드와 상수만으로 이루어져 있다.

- 단일 상속의 단점을 보완하여 다중 상속처럼 사용할 수 있는 기능을 제공한다.

특징

- 추상 클래스가 발전된 개념이므로, 인스턴스 생성이 불가능하다.

- 멤버로는 상수와 추상 메소드만 허용된다.

- 업캐스트 참조 변수로 사용할 수 있다.

- 하위 클래스에선 implements(구현) 관계이다.

- 하위 클래스에서는 여러 개의 인터페이스를 구현할 수 있다.

- 자바의 단일 상속 기능을 보완할 수 있다.

형식

public interface 인터페이스이름 {
    // 상수
    public static final 타입 상수이름 = 값;
    // 추상메소드
    public abstract 리턴타입 메소드이름(매개변수);
}

class 클래스이름 implements 인터페이스이름 {
    ...
}

상속과 인터페이스 동시 사용

- 동시 사용으로 다중 상속과 같은 효과를 얻을 수 있다.

public interface 인터페이스이름 {
    ...
}

public class 클래스이름 {
    ...
}

class 클래스이름 extends 클래스이름 implements 인터페이스이름 {
    ...
}

다중 인터페이스 사용

- 인터페이스와 인터페이스의 계층 구조 역시 상속 구조이다.

- 두 개의 인터페이스를 사용할 때는 콤마(,)로 구분하여 준다.

- 인터페이스는 클래스와 달리 다중 상속을 허용한다.
  하나의 인터페이스에서 다른 인터페이스 클래스를 다중 상속 받아 구현할 수 있다.

public interface 인터페이스이름1 {
    ...
}

public interface 인터페이스이름2 {
    ...
}

class 클래스이름 implements 인터페이스이름1, 인터페이스이름2 {
    ...
}

예제

// School 인터페이스
interface School {
    public static final int MAX_CLASS = 40;            // 학급수
    public static final int MAX_PERSON_PER_CLASS = 25; // 학급 당 학생수
    public abstract void printSchool();
}

// Student 클래스 - School 인터페이스 이용
class Student implements School {
    public void printSchool() {
        System.out.println("Dasan ByeolBit Elementary School");
    }
}

// Person 클래스
class Person {
    public String name;
    
    public void printName() {
        System.out.println("Name : " + name);
    }
}

// Student2 클래스 - Person 클래스 상속, School 인터페이스 이용
class Student2 extends Person implements School {
    Student2(String name) {
        super.name = name;
    }
    
    public void printSchool() {
        System.out.println("Kumkyo Elementary School");
    }
}

public class Main {
    public static void main(String[] args) {
        // 1. 인터페이스 기본 사용
        System.out.println("== 기본 인터페이스 ==");
        Student student = new Student();
        student.printSchool();                             // Dasan ByeolBit Elementary School
        System.out.println(student.MAX_CLASS);             // 40
        System.out.println(student.MAX_PERSON_PER_CLASS);  // 25
        
        // 2. 다중 상속처럼 사용하기
        System.out.println("== 다중 상속 사용 ==");
        Student2 student2 = new Student2("홍길동");
        student2.printSchool();                            // Kumkyo Elementary School
        student2.printName();                              // 홍길동
    }
}

⊙ 참고 문헌

  1. 이병승, 「초보 개발자를 위한 자바:한 권으로 배우는 자바 마스터 가이드 북」, 영진닷컴, 2024, p529 - 555
  2. 마종현, 「제로베이스 백엔드 취업 파트타임 스쿨 5기:Part 01. Java 기초-Chapter 01. Java 프로그래밍-10.인터페이스」, 제로베이스, 2024, https://zero-base.co.kr/