추상 메서드(메서드 선언만 있고 구현이 없는 메서드)와 상수만을 가질 수 있는 특별한 타입이다.
인터페이스는 클래스가 구현해야 할 동작(메서드)을 미리 정의해 두고, 이를 사용하는 클래스가 실제 내용을 구현한다.
interface 키워드로 정의한다.
| 항목 | 설명 |
|---|---|
| 키워드 | interface, implements |
| 다중 구현 | 클래스는 여러 인터페이스를 동시에 구현할 수 있음 |
| 접근 제어자 | 모든 필드는 public static final (값을 바꿀 수 없는 상수만 선언 가능), 모든 메서드는 public abstract (구현하지 않고 선언만 한다) |
| 상속과의 차이 | 클래스는 오직 하나의 클래스만 상속할 수 있지만, 인터페이스는 여러 개 구현 가능 |
인터페이스를 구현하는 클래스가 추상 클래스(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();
}
}
멍멍!
개가 네 발로 뜁니다.
짹짹!
새가 날아갑니다.
객체지향 설계 실습 : 다기능 로봇 시스템
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);
}
}