인터페이스

현서·2025년 5월 22일
1

자바

목록 보기
13/32
post-thumbnail

1. 인터페이스

  • 추상 메서드(메서드 선언만 있고 구현이 없는 메서드)와 상수만을 가질 수 있는 특별한 타입이다.

  • 인터페이스는 클래스가 구현해야 할 동작(메서드)을 미리 정의해 두고, 이를 사용하는 클래스가 실제 내용을 구현한다.

  • interface 키워드로 정의한다.

항목설명
키워드interface, implements
다중 구현클래스는 여러 인터페이스를 동시에 구현할 수 있음
접근 제어자모든 필드는 public static final (값을 바꿀 수 없는 상수만 선언 가능), 모든 메서드는 public abstract (구현하지 않고 선언만 한다)
상속과의 차이클래스는 오직 하나의 클래스만 상속할 수 있지만, 인터페이스는 여러 개 구현 가능
  • 인터페이스는 메서드의 '이름'과 '형태'만 정의해 놓은 계약서와 같다.
    인터페이스를 구현했다는 것은 "나는 이 계약을 지키겠다"는 뜻이며,
    그 계약된 메서드를 실제로 구현하지 않으면 컴파일 에러가 난다.

❗ 예외: abstract class로 구현한 경우

  • 인터페이스를 구현하는 클래스가 추상 클래스(abstract)라면,
    인터페이스의 모든 메서드를 구현하지 않아도 된다.

  • 하지만 그 추상 클래스를 상속한 일반 클래스는 반드시 남은 메서드를 구현해야 한다.

🔁 정리

상황오버라이딩 필요 여부
일반 클래스가 인터페이스 구현✅ 반드시 모든 메서드 오버라이딩
추상 클래스가 인터페이스 구현❌ 일부만 구현해도 가능
일반 클래스가 추상 클래스 상속✅ 남은 메서드 반드시 구현
package lesson05;

interface Ex04_Animal{
    int num = 10; // public static final int num = 10;
    void sound();
    void move();
}
class Ex04_Dog implements Ex04_Animal{
    @Override
    public void sound() {
        System.out.println("멍멍!");
    }

    @Override
    public void move() {
        System.out.println("개가 네 발로 뜁니다.");
    }
}

class Ex04_Bird implements Ex04_Animal{
    @Override
    public void sound() {
        System.out.println("짹짹!");
    }

    @Override
    public void move() {
        System.out.println("새가 날아갑니다.");
    }
}

public class Ex04_Main{
    public static void main(String[] args) {
        Ex04_Animal dog = new Ex04_Dog();
        Ex04_Animal bird = new Ex04_Bird();

        dog.sound();
        dog.move();
        bird.sound();
        bird.move();
    }
}
멍멍!
개가 네 발로 뜁니다.
짹짹!
새가 날아갑니다.

2. 종합예제

객체지향 설계 실습 : 다기능 로봇 시스템

package lesson05;

interface Cleaner {
    void clean();
}

interface Cooker {
    void cook();
}

interface Singer {
    void sing();
}

interface Dancer {
    void dance();
}

abstract class Robot {
    String modelName;

    public Robot(String modelName) {
        this.modelName = modelName;
    }

    public void identify() {
        System.out.println("안녕하세요! 저는 " + modelName + "로봇입니다.");
    }
}

class MultiRobot extends Robot implements Cleaner, Cooker, Singer, Dancer {
    public MultiRobot(String modelName){
        super(modelName);
    }

    @Override
    public void clean() {
        System.out.println("[" + modelName + "] 청소를 시작합니다.");
    }

    @Override
    public void cook() {
        System.out.println("[" + modelName + "] 요리를 시작합니다.");
    }

    @Override
    public void dance() {
        System.out.println("[" + modelName + "] 멋지게 춤을 시작합니다.");
    }

    @Override
    public void sing() {
        System.out.println("[" + modelName + "] 노래를 부릅니다.");
    }
}

public class Ex05_Main {
    public static void performFunction(Cleaner cleaner){
        cleaner.clean();
    }

    public static void performFunction(Cooker cooker){
        cooker.cook();
    }

    public static void performFunction(Singer singer){
        singer.sing();
    }

    public static void performFunction(Dancer dancer){
        dancer.dance();
    }

    public static void main(String[] args) {
        MultiRobot robot = new MultiRobot("Robo-X");
        robot.identify();
        robot.clean();
        robot.cook();
        robot.dance();
        robot.sing();

        performFunction((Cleaner) robot);
        performFunction((Cooker) robot);
        performFunction((Singer) robot);
        performFunction((Dancer) robot);
    }
}
profile
The light shines in the darkness.

0개의 댓글