에러 모음

ClassCastException

junani0v0 2024. 4. 2. 17:17

public class CastingMain4 {
    public static void main(String[] args) {
        Parent parent1 = new Child();
        Child child1 = (Child) parent1;
        child1.childMethod(); //문제 없음

        Parent parent2 = new Parent();
        Child child2 = (Child) parent2; //런타임 오류 - ClassCastException
        child2.childMethod(); //실행 불가
    }
}

 

< 에러 메시지 >

Exception in thread "main" java.lang.ClassCastException: class poly.Parent cannot be cast to class poly.Child (poly.Parent and poly.Child are in unnamed module of loader 'app')
at poly.CastingMAin4.main(CastingMAin4.java:10)

 

< 원인 >

parent2는 Parent로 생성 즉 부모타입으로 생성하였기에 메모리 상 자식타입이 존재하지 않아 다운캐스팅 하러라도 childMethod를 불러 올 수 없음

자바에서 사용할 수 없는 타입으로 다운캐스팅하는 경우 ClassCastException라는 런타임 예외 발생

 

<해결>

public static void main(String[] args) {
    Parent parent1 = new Child();
    call(parent1);

    Parent parent2 = new Parent();
    call(parent2);
}

private static void call(Parent parent) {
    if (parent instanceof Child) {
        System.out.println("Child 인스턴스 맞음");
        Child child = (Child) parent;
        child.childMethod();
    }else {
        System.out.println("Child 인스턴스 아님");
    }
}

 

 위 코드처럼 instanceof를 사용해 자식타입이 존재하는지 확인하는 코드를 추가하여 검증 후 사용

 

 Tip. instanceof 키워드는 오른쪽 대상의 자식타입을 왼쪽에서 참조하는 경우도 "true"반환.

쉽게 이야기해서 오른쪽에 있는 타입에 왼쪽에 있는 인스턴스의 타입이 들어갈 수 있는지 대입해보면 된다. 대입가능하면 "true", 불가능하면 "false"가 된다

'에러 모음' 카테고리의 다른 글

AssertionFailedError  (0) 2024.04.08
MissingServletRequestParameterException  (0) 2024.04.08
does not override abstract  (0) 2024.04.05
method does not override  (0) 2024.04.01
java.lang.StringIndexOutOfBoundsException 발생  (0) 2024.03.29