//개인공부기록용
// Animal 인터페이스 정의
interface Animal {
void fly();
void sing();
}
// CommonAnimal 추상 클래스: walk() 메서드를 가진 공통 추상 클래스
abstract class CommonAnimal {
// 일반 메서드
public void walk() {
System.out.println("걸을 수 있음");
}
// 추상 메서드 선언
public abstract void makeSound();
}
// Bird 클래스
class Bird extends CommonAnimal implements Animal {
public void fly() {
System.out.println("날을 수 있음");
}
public void sing() {
System.out.println("노래 부를 수 있음");
}
// makeSound() 메서드 구현
public void makeSound() {
System.out.println("짹짹 소리를 냅니다");
}
}
// Lion 클래스
class Lion extends CommonAnimal implements Animal {
public void fly() {
System.out.println("날 수 없음");
}
public void sing() {
System.out.println("노래 부를 수 없음");
}
// makeSound() 메서드 구현
public void makeSound() {
System.out.println("으르렁 소리를 냅니다");
}
}
// Rabbit 클래스
class Rabbit extends CommonAnimal implements Animal {
public void fly() {
System.out.println("날을 수 없음");
}
public void sing() {
System.out.println("노래 부를 수 없음");
}
// makeSound() 메서드 구현
public void makeSound() {
System.out.println("깡충깡충 소리를 냅니다");
}
}
// Tiger 클래스
class Tiger extends CommonAnimal implements Animal {
public void fly() {
System.out.println("날을 수 없음");
}
public void sing() {
System.out.println("노래 부를 수 없음");
}
// makeSound() 메서드 구현
public void makeSound() {
System.out.println("어흥 소리를 냅니다");
}
}
public class AnimalTest {
public static void main(String[] args) {
Bird bird = new Bird();
bird.walk();
bird.fly();
bird.sing();
bird.makeSound();
Lion lion = new Lion();
lion.walk();
lion.fly();
lion.sing();
lion.makeSound();
Rabbit rabbit = new Rabbit();
rabbit.walk();
rabbit.fly();
rabbit.sing();
rabbit.makeSound();
Tiger tiger = new Tiger();
tiger.walk();
tiger.fly();
tiger.sing();
tiger.makeSound();
}
}
추상클래스: 추상메서드, 일반메서드, 메서드 이외의 변수 등도 포함 가능. 단일 상속함.
인터페이스: 오직 메서드 선언만 가능. 이때 인터페이스 메서드는 추상메서드와 동일한 듯. 즉, 인터페이스 메서드==추상메서드. 다중 상속 가능함.
추상메서드, 인터페이스 메서드: 실제 구현 불가, 선언만 가능. 하위 클래스에서 해당 메서드를 반드시 구현해야 함.
추상클래스의 일반메서드는 하위 클래스에서 꼭 구현하지 않아도 됨. 공통 로직 구현할 때 쓸 수 있음.
[정리]
=> 인터페이스에서는 메서드 선언만 할 수 있고, 그 하위 클래스에서 각각 강제로 메서드를 구현해야 함. 하지만 추상클래스는 인터페이스의 메서드와 같은 특성을 가지는 추상메서드와 더불어 일반메서드도 가질 수 있음. 일반메서드는 추상클래스 안에서 메서드 선언뿐 아니라 구현도 가능하여 공통 로직을 구현할 수 있게 함. 그러나 추상클래스는 단일상속만 가능하다. 반면 인터페이스는 다중 상속이 가능하니 필요에 따라 적절히 사용하면 된다.