티스토리 뷰

Java+Spring/Java

[Java]instanceof 연산자

Vagabund.Gni 2022. 9. 19. 13:35
728x90
반응형

instanceof 연산자참조 변수의 타입 변환(캐스팅)이 가능한지 여부를 boolean 타입으로 알려주는 역할을 한다.

 

좀 더 직관적으로 받아들이기 위해 우선 사용법을 살펴보자. 문법은 아래와 같다.

A instanceof B

이때 instanceof 연산자는 A = B 이거나 A가 B를 상속받는 클래스인지를 boolean으로 알려준다고 할 수 있다.

 

그림으로 나타내면 대략 아래와 같다.

 

인터페이스의 경우에는 extends를 implements로 교체하면 동일한 로직을 적용할 수 있다.

 

예를 들어 AbstractSet 클래스를 상속받은 HashSet 객체의 경우 아래와 같은 결과를 얻을 수 있다.

HashSet set = new HashSet<>();

System.out.println(set instanceof HashSet);
System.out.println(set instanceof AbstractSet);
System.out.println(set instanceof Set);
System.out.println(set instanceof Collection);
System.out.println(set instanceof Object);
true
true
true
true
true

HashSet은 AbstractSet을 상속받고 AbstractSet은 Set을 구현하며 

 

Set은 Collection을 상속받고 모든 클래스는 Object를 상속받기 때문에

 

전부 true를 반환하게 된다.

 

반면 상속관계가 반대이거나 상속 관계가 아닌 인터페이스를 검증할 경우는 false를 리턴하게 되며,

HashSet set = new HashSet<>();

System.out.println(set instanceof LinkedHashSet);
System.out.println(set instanceof Map);
false
false

상속관계가 아닌 클래스를 검증 대상으로 집어넣을 경우 컴파일 에러가 발생하게 된다.

HashSet set = new HashSet<>();

System.out.println(set instanceof HashMap); // 컴파일 에러

또한 제네릭 클래스도 동일하게 검증할 수 있으나,

HashSet<String> set = new HashSet<>();

System.out.println(set instanceof HashSet);
System.out.println(set instanceof Set);
System.out.println(set instanceof Map);
System.out.println(set instanceof List);
true
true
false
false

타입이 결정되지 않은 제네릭 클래스컴파일 에러를 발생시킨다.

HashSet<T> set = new HashSet<>(); // 컴파일 에러

System.out.println(set instanceof HashSet);
System.out.println(set instanceof Set);
System.out.println(set instanceof Map);
System.out.println(set instanceof List);

마지막으로 A가 null이라면 instanceof는 상속관계와 상관없이 항상 false를 리턴하게 된다.

HashSet set = new HashSet<>();                    
set = null;

System.out.println(set instanceof HashSet);       
System.out.println(set instanceof Set);           
System.out.println(set instanceof Collection);    
System.out.println(set instanceof Object);
false
false
false
false

+)추가

 

같은 클래스를 상속받은 상태에서 상위 클래스 타입으로 클래스를 만들면

 

instanceof가 컴파일 에러가 아닌 false를 리턴한다.

Animal cat = new Cat();

System.out.println(cat instanceof Object);
System.out.println(cat instanceof Animal);
System.out.println(cat instanceof Cat);
System.out.println(cat instanceof Dog);

class Animal {};
class Dog extends Animal{};
class Cat extends Animal{};
true
true
true
false
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함