Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter03 : polymorphism 본문

JAVA/chapter16_polymorphism

chapter03 : polymorphism

GAWON 2023. 5. 26. 18:52
package org.joonzis.ex;
class Animal{
	public void move() {}
}
class Dog extends Animal{
	@Override
	public void move() {
		System.out.println("강아지 달린다.");
	}
}
class Dolphin extends Animal{
	@Override
	public void move() {
		System.out.println("돌고래 헤엄친다.");
	}
}
class Eagle extends Animal{
	@Override
	public void move() {
		System.out.println("독수리 움직이고.");
	}
	public void fly() {
		System.out.println("난다.");
	}
}
public class Ex03_polymorphism {
	public static void main(String[] args) {
		
		Animal[] animals = new Animal[3];
		
		// 업캐스팅
		animals[0] = new Dog();
		animals[1] = new Dolphin();
		animals[2] = new Eagle();
		
		for(int i=0; i<animals.length; i++) {
			animals[i].move();
		}
		
		//animals[2].fly();	// 부모 클래스는 fly() 메소드가 없기 때문에 호출할 수 없다.
		//((Eagle)animals[2]).fly();
		
		if(animals[2] instanceof Eagle) {
			// 다운 캐스팅
			// 1. Eagle 객체 생성
			Eagle eagle = (Eagle)animals[2];	
			eagle.fly();
			
			// 2. Eagle 객체 생성 없이 자원 사용
			((Eagle)animals[2]).fly();
		}
		
		
		
	}
}

'JAVA > chapter16_polymorphism' 카테고리의 다른 글

Test . polymorphism  (0) 2023.05.30
chapter04 : polymorphism  (0) 2023.05.26
chapter02 : polymorphism  (0) 2023.05.26
chapter01 : polymorphism  (0) 2023.05.26