instanceof는 어떻게 작동하나?

devhan·2023년 8월 3일

Runtime 기준

aObj instanceof Class / Interface

  • 좌항의 인스턴스가 우항의 클래스 혹은 서브클래스의 인스턴스인지 확인한다.
  • 런타임에 확인하기 때문에 실제 메모리의 인스턴스의 타입에 의해 결정된다.
  • 인터페이스에 대해서도 작동한다.
class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();

        if (animal instanceof Dog) {
            System.out.println("It's a Dog!");
        } else if (animal instanceof Cat) {
            System.out.println("It's a Cat!");
        } else {
            System.out.println("It's some other Animal.");
        }
        
        // It's a Dog
    }
}

null instanceof Object

정답은 false;
null은 누구의 instance도 아니다.

profile
한번에 한가지씩

0개의 댓글