728x90
반응형
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
}
}
왜 세번째는 false가 반환되었을까?
instanceof를 위에서 "객체 타입 확인", "형 변환 가능한지 여부 확인"이라 말했는데 어렵게 느껴진다면
쉽게 말해 instancof는 해당 클래스가 자기집이 맞는지 확인해 주는 것이라고 생각하면 될 것이다.
1. parent instanceof Parent : 부모가 본인 집을 찾았으니 true
2. child instanceof Parent : 자식이 상속받은 부모 집을 찾았으니 true (상속을 받았으니 자기 집이라 해도 무방하다?)
3. parent instanceof Child : 부모가 자식 집을 찾았으니 false (자식 집은 자식 집이지 부모 집은 아니니까)
4. child instanceof Child : 자식이 본인 집을 찾았으니 true
위에서 설명한 것과 마찬가지로 이러나저러나 본인이 이해하기 쉽게 받아들이면 될 것 같다.
누구한테는 하위 클래스니 상위 클래스니 하면서 접근하는 게 이해가 더 잘 될 수 있으니 말이다.
*형 변환이 불가능한 즉 타입이 상위 클래스도 하위 클래스도 아닐 경우에는 에러가 난다.
출처: https://mine-it-record.tistory.com/120 [나만의 기록들:티스토리]
728x90
반응형