instanceOf
연산자는 객체가 어떤 클래스인지, 어떤 클래스를 상속받았는지 확인하는데 사용하는 연산자입니다.
object가 type이거나 type을 상속받는 클래스라면 true를 리턴합니다. 그렇지 않으면 false를 리턴합니다.
object instanceOf type
class Parent {
}
class Child extends Parent {
}
public class Instanceof {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
Parent test1 = new Child();
//Child test2 = new Parent(); //불가능
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
System.out.println(test1 instanceof Child); //true
System.out.println(test1 instanceof Parent); //true
}
}
좀 더 자세히 설명하자면,
당연히 Parent가 부모이므로 Child 객체를 받을 수 있습니다.
하지만 실제로 test1이 참고하고 있는 객체는 Child입니다. 그렇기 때문에 test1을 Child로 변경가능합니다.
test1 instanceof Child
의 결과가 true가 나오는 이유입니다.
마찬가지로 Child의 부모는 Parent이기 때문에 test1 instanceof Parent
의 결과는 true가 나오게 됩니다.