개발공부/JAVA
[JAVA] instanceof
jnnjnn
2024. 3. 8. 18:00
어떤 객체가 해당 타입이 맞는지 확인할 때 사용하는 연산자이다.
boolean result = 객체 instanceof 타입
좌항의 객체가 우항의 타입이면 true, 그렇지 않으면 false를 산출한다.
자바 12부터는 instanceof 연산 결과가 true일 경우, 우측 타입 변수를 사용할 수 있다
class Parent {
method1(){}
}
class Child extends Parent {
method2(){}
}
public class C04InstanceOf {
public static void main(String[] args) {
Parent parent = new Child();
// 자바 12부터 가능
if(parent instanceof Child child) {
child.method2
}
}
// 위의 코드는 아래와 같음
if(parent instanceof Child){
Child child = (Child) parent;
}
}