다형성 - 다운캐스팅, instanceof

겨울조아·2023년 3월 14일
0

다형성 - 다운캐스팅, instanceof

import java.util.ArrayList;

class Animal {
	public void move() {
		System.out.println("동물이 움직입니다.");
	}
}

class Human extends Animal {
	public void move() {
		System.out.println("사람이 두 발로 걷습니다.");
	}
	public void readBooks() {
		System.out.println("사람이 책을 읽습니다.");
	}
}

class Tiger extends Animal {
	public void move() {
		System.out.println("호랑이가 네 발로 뜁니다.");
	}
	public void hunting() {
		System.out.println("호랑이가 사냥을 합니다.");
	}
}

class Eagle extends Animal {
	public void move() {
		System.out.println("독수리가 하늘을 날아갑니다.");
	}
	public void flying() {
		System.out.println("독수리가 날개를 펴고 날아갑니다. ");
	}
}

public class AnimalTest {

	public static void main(String[] args) {

		Animal hAnimal = new Human();
		Animal tAnimal = new Tiger();
		Animal eAnimal = new Eagle();

		// 방법 1
		ArrayList<Animal> animalList = new ArrayList<Animal>();
		animalList.add(hAnimal);
		animalList.add(tAnimal);
		animalList.add(eAnimal);

		// 방법 1, 리스트로 구현
		for (Animal ani : animalList) {
			ani.move();
		}

		// 방법 2, 클래스 하나 더 넣어서 구현
		animalMove(hAnimal);
		animalMove(tAnimal);
		animalMove(eAnimal);

	}

	// 방법 2 애니멀 타입으로 변환 => 업캐스팅
	private static void animalMove(Animal animal) {
		animal.move();
	}

	// hAnimal.readBooks();는 안됨 => 다운 캐스팅 해야함
	// 다운캐스팅 : 업캐스팅 된 클래스를 다시 원래의 타입으로 형 변환
	// 하위 클래스로의 형 변환은 명시적으로 해야함
	public static void testDownCasting(ArrayList<Animal> animalList) {

		for (int i = 0; i < animalList.size(); i++) {

			Animal animal = animalList.get(i);

			// instanceof 를 이용하여 인스턴스의 형 체크
			// 그냥 다운캐스팅해도 되긴하지만 오류가 날 수 있음
			if (animal instanceof Human) {
				Human human = (Human) animal;
				human.readBooks();
			} else if (animal instanceof Tiger) {
				Tiger tiger = (Tiger) animal;
				tiger.hunting();
			} else if (animal instanceof Eagle) {
				Eagle eagle = (Eagle) animal;
				eagle.flying();
			} else {
				System.out.println("error");
			}
		}
	}
}

0개의 댓글