[Java] instanceof 변수 선언

벼랑 끝 코딩·2025년 2월 24일
0

Java

목록 보기
17/40

instanceof

instanceof는 변수가 지정한 객체를 참조하는지 알 수 있는 키워드이다.

class Parent {
	// 코드
}

class Child extends new Parent {
	// 코드
}

public void instanceofMethod() {
	Parent parent = new Child();
    parent instanceof Child; // ** true **
    parent instanceof Parent; // ** true **
}

instanceof 활용

다운캐스팅을 사용할 때에는 런타임 오류가 발생할 수 있기 때문에
변수가 참조하는 인스턴스를 확인하고 객체를 생성하는 것이 중요하다.

다운 캐스팅의 위험성은 다음을 참고하자.

그렇다면 우리는 instanceof를 활용할 수 있겠다.

class Parent {
	// 코드
}

class Child extends new Parent {
	// 코드
}

public void instanceofMethod() {
	Parent parent = new Child();
    
    // parent가 Child를 참조하는 경우에만 다운캐스팅하여 자식 객체 메서드 실행
    if (parent instanceof Child) {
    	Child child = (child) parent;
        child.childMethod();
    }
}

하지만 다운캐스팅을 할 때마다 객체를 생성하는 것은 너무 복잡하다.

instanceof 변수 선언

여기 instanceof와 동시에 변수를 선언할 수 있는 방법이 있다.

public void instanceofMethod() {
	Parent parent = new Child();
    
    // ** parent 참조 확인과 동시에 객체 생성 **
    if (parent instanceof Child child) {
    	child.childMethod();
    }
}

마무리

instanceof 키워드는 종종 사용하는 키워드이기 때문에
변수를 동시에 선언할 수 있다는 것을 기억하고 써보도록 하자.

profile
복습에 대한 비판과 지적을 부탁드립니다

0개의 댓글