📌 Interface Exam1
package chap8;
/*
* Animal 클래스는 다음과 같다. 구동 클래스를 실행했을때 다음의 결과나
* 나오도록 프로그램 구현하기
* [결과]
* 비둘기는 작은 벌레를 잡아 먹는다.
* 비둘기는 날아 다니는 새입니다.
* 원숭이는 나무에서 열매를 따서 먹는다
* 독수리는 작은 새를 잡아 먹는다.
* 독수리는 엄청 높이 날아 다닌다.
*/
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
abstract void eat();
}
class Dove extends Animal implements Flyable{
Dove(){
super("비둘기");
}
void eat() {
System.out.println(name+"는 작은벌레를 잡아 먹는다.");
}
@Override
public void fly() {
System.out.println(name+"는 날아다니는 새입니다.");
}
}
class Monkey extends Animal{
Monkey(){
super("원숭이");
}
void eat() {
System.out.println(name+"는 나무에서 열매를 따서 먹는다.");
}
}
class Eagle extends Animal implements Flyable{
Eagle(){
super("독수리");
}
void eat() {
System.out.println(name+"는 작은 새를 잡아 먹는다.");
}
@Override
public void fly() {
System.out.println(name+"는 엄청 높이 날아다닌다.");
}
}
interface Flyable {
void fly();
}
public class Exam1 {
public static void main(String[] args) {
Animal[] arr = new Animal[3];
arr[0] = new Dove();
arr[1] = new Monkey();
arr[2] = new Eagle();
for(Animal a : arr) {
a.eat();
if(a instanceof Flyable) { //Dove,Eagle 객체는 Flyable 형변환 가능
Flyable f = (Flyable)a;//자동형변환 불가
f.fly();//Flyable 타입의 참조변수로 fly() 호출
}
}
}
}
'수업(국비지원) > Java' 카테고리의 다른 글
| [Java] chap9 : 예외처리 - Exception3(finally) (0) | 2023.04.15 |
|---|---|
| [Java] chap9 : 예외처리 - Exception1(try, catch), Exception2(다중 catch 구문) (0) | 2023.04.15 |
| [Java] chap8 : 인터페이스 - Interface(복합예제) (0) | 2023.04.15 |
| [Java] chap8 : 인터페이스 - Interface, 리턴타입이 인터페이스인 경우, 인터페이스의 객체화 (0) | 2023.04.15 |
| [Java] chap7 : 클래스의 관계 - Final 제한자, Final 메서드, Final 클래스 (0) | 2023.04.15 |