-
instanceof는 어떻게 작동하나?언어/자바 2023. 12. 20. 01:13
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도 아니다.'언어 > 자바' 카테고리의 다른 글
너무 다양한 List를 만드는 방법들.. (1) 2023.12.20 Queue의 add와 offer의 차이 (0) 2023.12.20 동적바인딩과 @Override (0) 2023.12.20 자바코드는 어떻게 실행되는가? <3> (0) 2023.12.18 자바코드는 어떻게 실행되는가? <2> (0) 2023.12.18