본문 바로가기

JAVA/JAVA Programming

[JAVA] instanceof 연산자(예약어)

반응형


■ instanceof 연산자(예약어)

-. instanceof 연산자가 기호로 되어 있지 않은 연산자이다.

-. instanceof 연산자는 유일하게 자바의 예약어로 되어 있는 연산자가 바로 instanceof 연산자다.


 배열의 타입이 Child인지 Parent인지 어떻게 구분해야 하는 경우 사용하는 것이 instanceof라는 예약어이다.



public class Inheritance {
    
    // 중간생략
    public void objectCast2() {

        Parent[] parentArray = new Parent[3];
        parentArray[0] = new Child();
        parentArray[1] = new Parent();
        parentArray[2] = new Child();

        for (Parent tempParent:parentArray) {

            if(tempParent instanceof Child) {
                
                System.out.println("Child");
            }

            else if(tempParent instanceof Parent) {
                
                System.out.println("Parent");
            }
        }
    }
}


-. instanceof의 앞에는 객체를, 뒤에는 클래스(타입)를 지정해 주면 된다. 그러면 이 문장은 true나 false와 같이 boolean 형태의 결과를 제공한다.

-. parentArray의 0번째 값은 Child 클래스의 객체이므로, [0] 값은 첫번째 if 문에서 true, [1] 값은 두번째 if 문에서 true, [2] 값은 첫번째 if 문에서 true여야 한다.


※ 컴파일 결과

Child

 Parent

 Child


반응형