본문 바로가기

Programming/JAVA

instanceof 연산자

boolean | instance instanceof class

instanceof 연산자는 객체가 어떤 클래스의 객체인지 확인할 때 쓰인다.

객체가 피연산자의 객체라면 true를, 그렇지 않다면 false를 반환한다.
이때 알아두어야 할 점은 해당 객체가 is a 관계를 가지고 있는 클래스 중
자식클래스에서 생성된 객체라 하더라도 피연산자가 부모클래스든 자식클래스든, true를 반환한다.

예를 들어
class A{}
class B extends A{}
이러한 관계일때 아래 구문을 모두 작성하여 실행한다면
A a = new A();
B b = new A();
system.out.println(b instanceof A);
system.out.println(b instanceof B);
system.out.println(a instanceof A);
system.out.println(a instanceof B);
system.out.println(a instanceof Object);

결과값은
true
true
true
false
true

이다.