다운캐스팅이란 상속관계에서 상속받은 자식클래스로 캐스팅 하는 것이다.

public class Animal {
	
	private String name;
	
	public void cry() {
		System.out.println(name + "가 소리를 낸다!!");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
public class Cat extends Animal{
	
//	private String name;
	
	// Animal 클래스의 함수도 모두 상속받는다.
	
	@Override
	public void cry() {
		// TODO Auto-generated method stub
		super.cry();
		System.out.println("야옹 야옹~~~");
	}
	
	void grooming() {
		System.out.println("그루밍 한다!");
	}
	
}
public class Dog extends Animal {

//	private String name;
	
	// Animal 클래스의 함수도 모두 상속받는다.

	@Override
	public void cry() {
		// TODO Auto-generated method stub
		super.cry();
		System.out.println("멍멍멍~~~~");
	}
	
	public void run() {
		System.out.println(getName() + "가 뛴다!!!");
	}
}
public class AnimalAction {
	
	void action(Animal animal) {
		
		animal.cry();
		
		if (animal instanceof Dog) {
			((Dog)animal).run(); 
		} else if (animal instanceof Cat) {
			((Cat)animal).grooming();
		}
	}
	
}
public class AnimalMain {

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

}
바둑이가 소리를 낸다!!
멍멍멍~~~~
바둑이가 뛴다!!!
키티가 소리를 낸다!!
야옹 야옹~~~
그루밍 한다!

Cat과 Dog 클래스는 Animal 클래스를 상속받았다. AnimalAction 클래스의 action 함수는 Animal 객체를 파라미터로 받는 데 이때 Cat과 Dog객체를 대입해서 업캐스팅이 일어나고 이 객체를 Dog나 Cat으로 다운캐스팅 하여 자식 클래스의 함수를 실행시킨다.

'자바' 카테고리의 다른 글

자바 인터페이스 사용방법  (0) 2022.07.06
자바 추상클래스 용도와 사용방법  (0) 2022.07.06
자바 업캐스팅이란?  (0) 2022.07.05
자바 super 부모생성자 호출  (0) 2022.07.05
자바 super 키워드  (0) 2022.07.04

+ Recent posts