자바(SE)

instanceof Class vs instanceof Interface

  • -
반응형

instanceof 연산자는 runtime에 객체의 실제 타입을 확인하기 위한 연산자이다.

instanceof 연산자를 사용하면서 compile error가 나는 경우를 정리해본다.

기본적으로 컴파일러는 클래스에 대한 정보만 관리한다.

interface MyInterface{}
class SuperClass{}
class SubClass extends SuperClass{}
class Some{}

A instanceof B를 사용할 때

1. A와 B가 모두 클래스일 경우 A는 반드시 B의 조상 클래스 타입이어야 한다.

// String은 Number의 하위 타입이 아니므로 오류
boolean b1 = "Hello" instanceof Number;
// SubClass는 Some 타입이 아니므로 오류
boolean b2 = new SubClass() instanceof Some;
// 정상
boolean b3 = new SubClass() instanceof SuperClass;

2. A가 클래스이고 B가 인터페이스일 경우

컴파일 타임에서는 A가 B를 구현했는지 알 수 없다. 따라서 실제 인터페이스 구현 여부와 상관없이 instanceof를 사용할 수 있다.

boolean b4 = new SubClass() instanceof MyInterface;	// 정상	
// 컴파일 타임에 Some과 interfcce관계는 알 수 없다.
boolean b5 = new Some() instanceof MyInterface;	   // 정상

3. 하지만 A가 final 클래스인 경우는 이미 고정된 경우이므로 클래스에 명시된 인터페이스와 비교만 가능하다.

// final 클래스는 interface도 불가
boolean b6 = "Hello" instanceof MyInterface;
// 기본으로 implements 된 interface는 사용 가능
boolean b7 = "Hello" instanceof Serializable;

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.