💡 객체를 생성하면 부모 타입은 모두 함께 생성되지만 자식 타입은 생성되지 않는다
다운캐스팅 그림

A a = new B() : A로 업케스팅B b = new B() : 자신과 같은 타입C c = new B() : 하위 타입은 대입할 수 없음, 컴파일 오류C c = (C) new B() : 하위 타입으로 강제 다운캐스팅, 하지만 B 인스턴스에 C와 관련된 부분이 없으므로 잘못된 캐스팅, ClassCastException 런타임 오류 발생그러면 참조하는 대상이 다양할때 어떤 인스턴스를 참조하고 있는지 확인하려면 어떻게 해야할까
⇒ 인스턴스의 타입을 확인하고 싶다면 instanceof 키워드를 사용하면 된다.
public class CastingMain6 {
public static void main(String[] args) {
Parent parent1 = new Parent();
System.out.println("parent1 호출");
call(parent1);
Parent parent2 = new Child();
System.out.println("parent2 호출");
call(parent2);
}
private static void call(Parent parent) {
parent.parentMethod();
//자바 16부터는 instanceof 를 사용하면서 동시에 변수를 선언할 수 있다
//Child 인스턴스인 경우 childMethod() 실행
if (parent instanceof Child child) {
System.out.println("Child 인스턴스 맞음");
child.childMethod();
}
}
}
실행결과
parent1 호출
Parent.parentMethod
parent2 호출
Parent.parentMethod
Child 인스턴스 맞음
Child.childMethod
💡 기억해야 할 점은 오버라이딩 된 메서드가 항상 우선권을 가진다는 점

poly.method() : Parent 타입에 있는 method() 를 실행하려고 한다. 그런데 하위 타입Child.method()가 오버라이딩 되어 있다. 오버라이딩 된 메서드는 항상 우선권을 가진다. 따라서 Parent.method() 가 아니라 Child.method() 가 실행된다.