instanceof - 캐스팅 사용시 해당 객체에 무엇이 들어있는지 확인?

  • 다형성에서 참조형 변수는 다양한 자식을 대상으로 참조할 수 있다. → 하지만 어떤 객체를 참조 하는지 확인 하려 할때 사용 한다.

→ instanceof 사용 예 🔽

package poly.basic;

public class CastingMain5 {
    public static void main(String[] args) {
        Parent parent1 = new Parent();
        System.out.println("parent1 호출");
        call(parent1);

        System.out.println("--------");

        Parent parent2 = new Child();
        System.out.println("parent2 호출");
        call(parent2);

    }

    private static void call (Parent parent) {
        parent.parentMethod();

        if (parent instanceof Child) { 
		        // <- 객체의 타입을 instanceof 를 사용하여 비교 할 수 있다.
            System.out.println("Child 인스턴스 맞음");
            Child child = (Child) parent;
            child.childMethod();
        } else {
            System.out.println("Child 인스턴스 아님");
        }
    }
}

→ instanceof 실행 결과 🔽

parent1 호출
Parent.parentMethod
Child 인스턴스 아님
--------
parent2 호출
Parent.parentMethod
Child 인스턴스 맞음
Child.childMethod

instanceof 사용 이해 하기

  • instanceof 키워드는 오른쪽 대상타입이 왼쪽에 있는 타입에 포함되어 있는지 여부를 판단한다고 생각하면 된다.
new Parent() instanceof Parent // true -> 자기 자신 내에는 자신 영역이 존재
new Child() instanceof Parent // true -> 자식 객체 내에는 부모 영역도 존재

Java16 버전 부터 - Pattern Matching for instanceof

  • instancof 를 사용하면서 동시에 변수 선언 까지 하는 것

→ 이런식으로 사용가능하다.


 

+ Recent posts