Java
[Interface & Extends] 이 둘의 단순하지만 OOP적인 Collaboration
고인돌개발자
2021. 5. 6. 22:26
학습목표 : 인터페이스와 상속의 조화로운 모습을 이해한다.
* 내용은 단순하기 때문에 클래스 구조와 소스를 직접 실행해보면
상속과 인터페이스를 별개로 생각하기 보다는 서로 연결되는 부분이 있다는 점을 생각할 수 있습니다.
클래스 구조

2. 소스코드
package book.oopforsprings.lec03.ver04_interface_plus_extends;
/*
* The collaboration of Interface and Extends
*/
public class Interface_plus_Extends {
public static void main(String[] args) {
IfFly bat = new Bat();
bat.fly();
IfFly sparrow = new Sparrow();
sparrow.fly();
/* Use Array */
IfSwim ifswim[] = new IfSwim[2];
ifswim[0] = new Whale();
ifswim[1] = new Penguin();
for(IfSwim array_swim: ifswim) {
array_swim.swim();
}
}
}
/* Super Class */
class Animal{
String myClass;
public Animal() {
myClass = "Animal";
}
}
/* Interface */
interface IfFly {
void fly();
}
/* Interface */
interface IfSwim{
void swim();
}
/* Inheritance */
class Mammal extends Animal{
public Mammal() {
myClass = "Mammal";
}
}
/* Inheritance */
class Bird extends Animal{
public Bird() {
myClass = "Bird";
}
}
/* Collaboration */
class Whale extends Mammal implements IfSwim{
public Whale() {
myClass = "Whale";
}
@Override
public void swim() {
System.out.println(myClass + " -> Swimming ... ");
}
}
/* Collaboration */
class Bat extends Mammal implements IfFly{
public Bat() {
myClass = "Bat";
}
@Override
public void fly() {
System.out.println(myClass + " -> Flying ... ");
}
}
/* Collaboration */
class Sparrow extends Bird implements IfFly{
public Sparrow() {
myClass = "Sparrow";
}
@Override
public void fly() {
System.out.println(myClass + " -> Flying ... ");
}
}
/* Collaboration */
class Penguin extends Bird implements IfSwim{
public Penguin() {
myClass = "Penguin";
}
@Override
public void swim() {
System.out.println(myClass + " -> Swimming ... ");
}
}