[Java 객체지향] 다운 캐스팅과 instanceof

2022. 1. 31. 22:02·Java & Kotlin

다운 캐스팅

  • 업캐스팅이 된 인스턴스가 원래 자신의 타입으로 형 변환 하는 것이다.
  • 명시적으로 해주어야 함
Customer vc = new VIPCustomer();		// 묵시적
VIPCustomer vCustomer = (VIPCustomer)vc;	// 명시적

 

instanceof

VIPCustomer vc = (VIPCustomer)customerPark;
  • GoldCustomer 타입의 인스턴스인 customerPark을 VIPCustomer 클래스로 형변환하려고 하면 run시 오류가 난다. (컴파일 오류는 X → 이클립스는 인스턴스의 타입까지는 알 수 없음)
  • 이럴 경우 인스턴스의 타입을 확인해주는 조건문이 필요하다.
  • 이때 사용되는 키워드가 instanceof이다.
if(customerPark instanceof VIPCustomer) {	// customerPark이 VIP 타입인지 확인
    VIPCustomer vc = (VIPCustomer)customerPark;
}

 

예제 코드

AnimalTest.java
// 각 클래스 구현부 생략
public class AnimalTest {

	public static void main(String[] args) {
		
		Animal hAnimal = new Human();	// 상위 클래스로 각 하위 인스턴스 생성
		Animal tAnimal = new Tiger();
		Animal eAnimal = new Eagle();
		
		ArrayList<Animal> animalList = new ArrayList<>();	// Animal 타입의 ArrayList 생성
		animalList.add(hAnimal);	// 각 인스턴스 넣어줌
		animalList.add(tAnimal);
		animalList.add(eAnimal);
		
		AnimalTest test = new AnimalTest();
		test.testDownCasting(animalList);
		
	}
	
	public void testDownCasting(ArrayList<Animal> list) {
		
		for ( int i = 0 ; i < list.size() ; i ++ ) {
			Animal animal = list.get(i);
			
			if(animal instanceof Human) {
				Human human = (Human)animal;
				human.readBook();
			}
			
			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");
			}
		}
	}

}

 

수행 결과

ArrayList에 저장된 인스턴스를 순서대로 타입을 확인해서 메서드를 수행하였다.

사람이 책을 읽습니다.
호랑이가 사냥을 합니다.
독수리가 날개를 펴고 멀리 날아갑니다.

 

AnimalTest.class 코드에서 볼 수 있듯이 다운 캐스팅을 사용하게 되면 코드가 지저분해질 수 있기 때문에 되도록 다형성을 활용하는 것이 깔끔하다.

저작자표시 비영리 변경금지 (새창열림)

'Java & Kotlin' 카테고리의 다른 글

[Java 객체지향] 추상 클래스  (0) 2022.02.01
[Java 객체지향] 다형성  (0) 2022.01.31
[Java 객체지향] 메서드의 재정의와 가상 메서드 원리  (0) 2022.01.31
'Java & Kotlin' 카테고리의 다른 글
  • [Java 객체지향] 추상 클래스 활용 (템플릿 메서드 패턴)
  • [Java 객체지향] 추상 클래스
  • [Java 객체지향] 다형성
  • [Java 객체지향] 메서드의 재정의와 가상 메서드 원리
Sue
Sue
개발 공부 로그
  • Sue
    Sue's devlog
    Sue
  • 전체
    오늘
    어제
    • 분류 전체보기 (122)
      • Algorithm (2)
      • WEB (8)
      • Java & Kotlin (83)
      • Spring (26)
      • Database (1)
      • Infra (0)
      • Git (1)
      • devlog (1)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Sue
[Java 객체지향] 다운 캐스팅과 instanceof
상단으로

티스토리툴바