프로그래밍/Java
[Java, 자바] instanceof란 ?
차나니
2024. 4. 13. 10:00
instanceof란 ?
instanceof는 객체 타입을 확인하는 연산자입니다 !
형변환 가능 여부를 확인하여 true/false로 결과를 반환해줍니다. 주로 상속 관계에서 부모 객체인지 자식 객체인지 확인하는 데 사용됩니다 !
instanceof 사용방법
instanceof의 기본 사용방법은 아래의 예시와 같이 "객체 instanceof 클래스"를 선언함으로써 사용할 수 있습니다.
class Parent{}
class Child extends Parent{}
public class InstanceofTest {
public static void main(String[] args){
Parent parent = new Parent();
Child child = new Child();
System.out.println( parent instanceof Parent ); // true
System.out.println( child instanceof Parent ); // true
System.out.println( parent instanceof Child ); // false
System.out.println( child instanceof Child ); // true
}
}
쉽게 정리하면 instanceof는 해당 클래스가 자기집이 맞는지 확인해 주는 것이라고 생각하면 됩니다 !
1. parent instanceof Parent : 부모가 본인 집을 찾았으니 true
2. child instanceof Parent : 자식이 상속받은 부모집을 찾았으니 true (상속을 받았으니 자기 집이라 해도 무방합니다.)
3. parent instanceof Child : 부모가 자식 집을 찾았으니 false
4. child instanceof Child : 자식이 본인 집을 찾았으니 true
형 변환이 불가능한 즉 타입이 상위 클래스도 하위 클래스도 아닐 경우에는 에러가 발생하는 점 주의하세요 !!!!!!