Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발자 도전기

[JAVA] instanceof 본문

개발공부/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;
    }
}