Java

인터페이스

KJihun 2023. 5. 25. 16:50
728x90
인터페이스란?

자바에서 인터페이스는 두 가지의 의미가 있다.

  1. 두 객체를 연결해 주는 다리 역할
  2. 상속관계가 없는 다른 클래스들이 동일한 메서드(동일한 행위)를 구현해야 할 때 사용하는 메서드

이 글에선 2번의 인터페이스에 대해 설명한다.

 

  • 인터페이스는 다중 상속이 가능하다.
  • 인터페이스의 추상 메서드는 구현될 때 반드시 오버라이딩 되어야 한다.
  • 만약 인터페이스의 추상 메서드를 일부만 구현해야 한다면 해당 클래스를 추상 클래스로 변경하여 사용할 수 있다.      아래에 예시 코드를 작성함.
  • 모든 멤버는 static final모드 메서드는 public abstract 이어야 한다.                                                                          생략 가능하며 생략 시 컴파일러가 자동으로 추가해 준다.(static메서드와 default메서드 제외)

 

  • 선언방법: public interface 인터페이스명 { ... }
  • 구현방법: public class 클래스명 implements 인터페이스명 { ... }
  • 인터페이스 간 상속 시 implements가 아닌 extends 키워드를 사용한다. 

예시 코드

//인터페이스 선언부
public interface Animal {
    void eat();
    void sleep();
    void makeSound();
}
 //인터페이스 구현부
public class Cat implements Animal {
	
    @Override
    public void eat() {
        System.out.println("고양이가 먹고 있습니다.");
    }
	@Override
    public void sleep() {
        System.out.println("고양이가 자고 있습니다.");
    }
	@Override
    public void makeSound() {
        System.out.println("야옹!");
    }
}

public class Dog implements Animal {
    public void eat() {
        System.out.println("강아지가 먹고 있습니다.");
    }

    public void sleep() {
        System.out.println("강아지가 자고 있습니다.");
    }

    public void makeSound() {
        System.out.println("멍멍!");
    }
}
//인터페이스의 추상 메서드를 일부만 구현해야 할 때, 해당 클래스를 추상 클래스로 변경하는 코드
interface Animal {
    void eat();
    void sleep();
    void makeSound();
}

//먹는 소리만 구현하고 싶을 때
abstract class AbstractAnimal implements Animal {
    public void eat() {
        System.out.println("동물이 먹고 있습니다.");
    }
//이후 메서드는 상속받는 자식 클래스에서 재정의(overriding) 하여 사용할 수 있다
    public abstract void sleep();
    public abstract void makeSound();
}

//AbstractAnimal의 자식클래스. 상속받은 후 구현되지 않은 메서드를 구현하여 사용
class Cat extends AbstractAnimal {
    public void sleep() {
        System.out.println("고양이가 자고 있습니다.");
    }

    public void makeSound() {
        System.out.println("야옹!");
    }
}

class Dog extends AbstractAnimal {
    public void sleep() {
        System.out.println("강아지가 자고 있습니다.");
    }

    public void makeSound() {
        System.out.println("멍멍!");
    }
}

public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat(); // "동물이 먹고 있습니다." 출력
        cat.sleep(); // "고양이가 자고 있습니다." 출력
        cat.makeSound(); // "야옹!" 출력

        Dog dog = new Dog();
        dog.eat(); // "동물이 먹고 있습니다." 출력
        dog.sleep(); // "강아지가 자고 있습니다." 출력
        dog.makeSound(); // "멍멍!" 출력
    }
}

'Java' 카테고리의 다른 글

default 메서드, static 메서드  (0) 2023.05.26
인터페이스와 추상 클래스의 차이  (0) 2023.05.25
추상 클래스  (0) 2023.05.25
super와 super()  (0) 2023.05.24
생성자란? this와 this()의 차이  (0) 2023.05.24