카테고리 없음

JAVA - 상속관계의 클래스에 대한 캐스팅 - 다운캐스팅(DownCasting)

Cong_S 2022. 7. 5. 17:40

앞선 업캐스팅과는 정반대의 개념이다.

https://cong-s.tistory.com/206

 

JAVA - 상속관계의 클래스에 대한 캐스팅 - 업캐스팅(UpCasting)

업캐스팅이란? (Type, 형 변환) 자식 클래스의 객체를 부모 클래스의 타입으로 변환하는 것을 말한다. public class UpCastingParent { int x; int y; } public class UpCastingChild extends UpCastingParent { /..

cong-s.tistory.com

업캐스팅과의 가장 큰 차이점은 명시적으로 타입 변환을 지정해야한다는 점이다.

 

// 부모 클래스 Animal 클래스
public class Animal {
	
	private String name;
}

// 자식 클래스 Dog 클래스
public class Dog extends Animal {
}

// 자식 클래스 Cat 클래스

public class Cat extends Animal {
}

 

위 클래스들 활용해 다운캐스팅으로 action 함수를 작동시켜보자.

public class AnimalAction {
		// 제일 최상위 클래스로 파라미터를 받아주면 모든 코드를 실행시킬 수 있다.
	void action(Animal animal) { // Animal animal = new Dog();
		// 각각 animal에게 상속받은 cry 함수 (공통된 함수)
	animal.cry();
	
		// 각자 고유한 함수
		if (animal instanceof Dog) {
			((Dog)animal).run();
		} else if (animal instanceof Cat) {
			((Cat)animal).grooming();
		}
	}
}

 

실제 작동하는 main 함수 코드

public class AnimalMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		AnimalAction action = new AnimalAction();
		
		Dog d = new Dog();
		d.setName("바둑이");
		
		Cat c = new Cat();
		c.setName("쿠키");
		
		action.action(c);
	}

}

action 함수의 시작 부분에서 부모 클래스에서 animal 이라는 변수를 만들어오고
다운캐스팅으로 자식 클래스 객체인 Dog를 부모클래스인 animal 로 지정한 것이다.

위 과정을 통해 파라미터 속 Animal animal 의 실제 의미는 new Dog(); 이다.

다시 말해, 자식 클래스로 지정되었다는 것을 알 수 있다.