개발/Java

Java에서 instanceof 연산자

ju_ni_ 2023. 7. 18. 15:55
반응형

instanceofJava에서 제공하는 특별한 키워드로, 주어진 객체가 특정 클래스 혹은 그 서브 클래스의 인스턴스인지를 검사할 때 사용합니다. 이 연산자는 객체 지향 프로그래밍의 다형성 개념과 밀접하게 관련되어 있습니다.

 

instanceof 연산자란?

instanceof 연산자는 주어진 객체가 특정 클래스의 인스턴스이거나 그 서브 클래스의 인스턴스인지를 확인하는 데 사용됩니다. 이 연산자의 결과는 불리언 형식으로 반환됩니다. 객체가 해당 클래스 혹은 그 서브 클래스의 인스턴스라면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

public class Main {
  public static void main(String[] args) {
    String s = "Hello";
    if (s instanceof String) {
      System.out.println("s는 String의 인스턴스입니다.");
    }
  }
}

위 예시에서, "Hello"라는 문자열은 String 클래스의 인스턴스이므로 s instanceof String의 결과는 true가 되어 "sString의 인스턴스입니다."라는 메시지가 출력됩니다.

 

instanceof 연산자와 클래스 상속

instanceof는 상속 계층 구조를 가진 클래스들과 함께 사용될 때 특히 유용합니다. 부모 클래스의 참조 변수로 자식 클래스의 객체를 참조하는 상황에서, 원래 객체가 어떤 클래스의 인스턴스인지 확인할 수 있습니다.

class Parent {}
class Child extends Parent {}

public class Main {
  public static void main(String[] args) {
    Parent parent = new Parent();
    Child child = new Child();
    Parent parentChild = 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(parentChild instanceof Child); // true
  }
}

위 예시에서, parentChildParent 클래스 타입의 참조 변수이지만 실제로는 Child 클래스의 객체를 참조하고 있습니다. 따라서 parentChild instanceof Child의 결과는 true입니다.

반응형