[JAVA] 객체 지향 핵심 - 다운 캐스팅, instanceof

WOOK JONG KIM·2022년 8월 31일
0

패캠_java&Spring

목록 보기
6/103
post-thumbnail

다운 캐스팅

  • 업캐스팅된 클래스를 다시 원래의 타입으로 형 변환
  • 하위 클래스로의 형 변환은 명시적으로 해야 함
Customer vc = new VIPCustomer();              //묵시적
VIPCustomer vCustomer = (VIPCustomer)vc;      //명시적

instanceof

원래 인스턴스의 형이 맞는지 여부를 체크하는 키워드 맞으면 true 아니면 false를 반환 함

public void testDownCasting(ArrayList<Animal> list) {
		
		for(int i =0; i<list.size(); i++) {
			Animal animal = list.get(i);
		// animal을 Human 으로 
			if ( animal instanceof Human) {
				Human human = (Human)animal;
				human.readBooks();
			}
       // animal을 Tiger로      
			else if( animal instanceof Tiger) {
				Tiger tiger = (Tiger)animal;
				tiger.hunting();
			}
       // animal을 Eagle로     
			else if( animal instanceof Eagle) {
				Eagle eagle = (Eagle)animal;
				eagle.flying();
			}
			else {
				System.out.println("error");
			}
		
		}
}
profile
Journey for Backend Developer

0개의 댓글