instanceof
- instanceof는 객체 타입을 확인하는 연산자이다.
- 형변환 가능 여부를 확인하며 true / false로 결과를 반환한다.
- 주로 상속 관계에서 부모객체인지 자식 객체인지 확인하는 데 사용된다.
instanceof의 기본 사용방법은 "객체 instanceof 클래스" 를 선언함으로써 사용한다.
다음 예제로 어떤 구조인지 파악해 보자
class Parent{}
class Child extends Parent{}
public class InstanceofTest {
public static void main(String[] args){
Parent parent = new Parent();
Child child = new Child();
System.out.println( parent instanceof Parent ); // true
System.out.println( child instanceof Parent ); // true
System.out.println( parent instanceof Child ); // false
System.out.println( child instanceof Child ); // true
}
}
A instanceof B //
A가 B의 (인스턴스) 라면 true.
즉, A가 B에 포함되면 true
즉, A가 B의 자식클래스거나 자기자신이면 true
'TIL' 카테고리의 다른 글
디자인 패턴이란 (0) | 2022.11.15 |
---|---|
Scheduler vs Spring batch vs DB Procedure (0) | 2022.11.08 |
Annotation이란? (0) | 2022.11.08 |
자바 Static 왜 쓰는지. (0) | 2022.11.03 |
ER 다이어그램 정리 (0) | 2022.11.02 |