상속의 핵심:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // 상속된 메서드
dog.bark(); // Dog 클래스에서 정의된 메서드
}
}
인터페이스의 핵심:
implements
키워드로 구현.interface Flyable {
void fly();
}
interface Swimable {
void swim();
}
class Bird implements Flyable {
public void fly() {
System.out.println("The bird can fly.");
}
}
class Duck implements Flyable, Swimable {
public void fly() {
System.out.println("The duck can fly.");
}
public void swim() {
System.out.println("The duck can swim.");
}
}
public class Main {
public static void main(String[] args) {
Duck duck = new Duck();
duck.fly(); // Flyable 인터페이스 구현
duck.swim(); // Swimable 인터페이스 구현
}
}
기준 | 상속 | 인터페이스 |
---|---|---|
의미 | 상위 클래스의 속성과 메서드 물려받음 | 특정 행동(메서드) 구현 강제 |
관계 | is-a 관계 | can-do 관계 |
사용 방식 | extends 키워드 사용 | implements 키워드 사용 |
다중 사용 | 단일 상속만 가능 | 다중 구현 가능 |
목적 | 코드 재사용 및 계층 구조 | 행동(기능)의 계약 정의 |
상속을 사용해야 할 때:
강한 is-a 관계가 성립될 때.
공통된 기능을 재사용하거나 확장할 때.
예: Vehicle → Car, Bike
인터페이스를 사용해야 할 때:
특정 동작만을 정의해야 할 때.
클래스가 서로 다른 계층에서 공통된 행동을 구현해야 할 때.
예: Flyable → Bird, Plane
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
interface Flyable {
void fly();
}
class Bird extends Animal implements Flyable {
public void fly() {
System.out.println("This bird can fly.");
}
}
public class Main {
public static void main(String[] args) {
Bird bird = new Bird();
bird.eat(); // 상속된 메서드
bird.fly(); // 인터페이스 구현 메서드
}
}
상속은 재사용과 확장에 중점을 두고, 인터페이스는 행동 보장에 중점을 둡니다.
유연한 설계를 위해 두 개념을 적절히 조합해 사용하는 것이 중요합니다.