부모 타입이면 모두 자식 타입으로 강제 타입 변환할 수 있는 것은 아님

부모 → 자식 변환 전, 부모 변수가 참조하는 객체가 자식 객체인지 확인하는 방법 = instanceof 사용

 

타입 확인 없이 강제 타입 변환을 시도한다면, ClassCastException 예외가 발생할 수 있다.

 

boolean result = A객체 instanceof B타입;

: A객체가 B타입이냐?

public void method(Parent parent) {
	if(parent instanceof Child) {
		Child child = (Child) parent;
    }
}

 

부모 클래스

package sec07.exam07_instanceof;

public class Parent {

}

 

자식 클래스

package sec07.exam07_instanceof;

public class Child extends Parent {

}

 

객체 타입 확인

package sec07.exam07_instanceof;

public class InstanceofExample {
	public static void method1(Parent parent) {
		if(parent instanceof Child) {
			Child child = (Child) parent; //부모->자식으로의 강제 타입 변환
			System.out.println("instanceof 사용 method1 - Child로 변환 성공");
		} else {
			System.out.println("instanceof 사용 method1 - Child로 변환되지 않음");
		}
	}
	
	public static void method2(Parent parent) {
		Child child = (Child) parent; //ClassCastException 발생 가능성 존재
		System.out.println("instanceof 사용 안한 method2 - Child로 변환 성공");
	}
	
	public static void main(String[] args) {
		Parent parentA = new Child(); //자식->부모로 자동 타입 변환
		method1(parentA); //instanceof 사용하여 조사한 후 true 나와서 변환 성공
		method2(parentA); //자식->부모로 자동타입변환 후 부모->자식으로 강제타입변환은 가능하므로 변환 성공
		                                    
		Parent parentB = new Parent(); //자식->부모로의 자동 타입 변환이 아니라, 그냥 부모 클래스의 인스턴스 생성임 : 추후 부모->자식으로의 강제타입변환 불가
		method1(parentB); //instanceof 사용하여 조사한 후 false 나와서 변환 실패
		method2(parentB); //instanceof 사용하지 않고 강제타입변환(부모->자식) 시도했더니 ClassCastException 발생
	}
	
}
instanceof 사용 method1 - Child로 변환 성공
instanceof 사용 안한 method2 - Child로 변환 성공
instanceof 사용 method1 - Child로 변환되지 않음
Exception in thread "main" java.lang.ClassCastException: class sec07.exam07_instanceof.Parent cannot be cast to class sec07.exam07_instanceof.Child (sec07.exam07_instanceof.Parent and sec07.exam07_instanceof.Child are in unnamed module of loader 'app')
	at sec07.exam07_instanceof.InstanceofExample.method2(InstanceofExample.java:14)
	at sec07.exam07_instanceof.InstanceofExample.main(InstanceofExample.java:25)

+ Recent posts