Java 에서 객체가 클래스의 인스턴스인지 확인하는 방법

JavaBeginner
지금 연습하기

소개

이 랩에서는 Java 에서 instanceof 키워드를 사용하여 객체가 특정 클래스 또는 인터페이스의 인스턴스인지 확인하는 방법을 배우게 됩니다. 기본 사용법을 살펴보고, 하위 클래스에서의 동작을 테스트하며, null 객체를 처리하는 방식을 이해할 것입니다.

실습 예제를 통해 런타임 타입 검사 (runtime type checking) 를 수행하기 위해 instanceof를 사용하는 실질적인 경험을 얻게 될 것입니다. 이는 객체 지향 프로그래밍의 기본적인 개념입니다.

instanceof 를 사용한 클래스 확인

이 단계에서는 Java 에서 instanceof 키워드를 살펴보겠습니다. instanceof 키워드는 객체가 특정 클래스의 인스턴스인지 또는 특정 인터페이스를 구현하는지 테스트하는 데 사용됩니다. 런타임에 객체의 타입을 확인하는 데 유용한 도구입니다.

instanceof가 어떻게 작동하는지 보여주는 간단한 Java 프로그램을 만들어 보겠습니다.

  1. WebIDE 를 열고 ~/project 디렉토리에 있는지 확인합니다. 터미널 프롬프트를 보거나 pwd를 입력하고 Enter 키를 눌러 확인할 수 있습니다.

  2. ~/project 디렉토리에 TypeCheck.java라는 새 Java 파일을 만듭니다. 왼쪽의 파일 탐색기에서 마우스 오른쪽 버튼을 클릭하고 "New File"을 선택한 다음 TypeCheck.java를 입력하여 이 작업을 수행할 수 있습니다.

  3. 편집기에서 TypeCheck.java 파일을 열고 다음 코드를 붙여넣습니다.

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
        }
    }

    이 코드에서:

    • 기본 클래스 Animal과 두 개의 하위 클래스 DogCat을 정의합니다.
    • main 메서드에서 Animal 변수 myAnimal을 생성하고 Dog 객체를 할당합니다. DogAnimal의 한 유형이므로 가능합니다.
    • 그런 다음 instanceof 키워드를 사용하여 myAnimalDog, CatAnimal의 인스턴스인지 확인합니다.
  4. TypeCheck.java 파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

  5. WebIDE 하단의 터미널을 열고 다음 명령을 실행하여 Java 프로그램을 컴파일합니다.

    javac TypeCheck.java

    오류가 없으면 이 명령은 ~/project 디렉토리에 TypeCheck.class, Animal.class, Dog.classCat.class 파일을 생성합니다.

  6. 다음 명령을 사용하여 컴파일된 프로그램을 실행합니다.

    java TypeCheck

    다음과 유사한 출력을 볼 수 있습니다.

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal

    이 출력은 Dog 객체를 포함하는 myAnimal이 실제로 Dog의 인스턴스이고 상위 클래스 Animal의 인스턴스이기도 하지만 Cat의 인스턴스는 아님을 확인합니다.

Java 에서 instanceof 키워드를 사용하여 객체의 타입을 성공적으로 확인했습니다. 다음 단계에서는 instanceof가 하위 클래스에서 어떻게 동작하는지 살펴보겠습니다.

하위 클래스 테스트

이전 단계에서 객체가 자체 클래스의 인스턴스이고 상위 클래스의 인스턴스이기도 하다는 것을 확인했습니다. instanceof가 서로 다른 객체 유형과 해당 하위 클래스에서 어떻게 작동하는지 자세히 살펴보겠습니다.

Cat 객체로 instanceof를 테스트하기 위해 기존 TypeCheck.java 파일을 수정합니다.

  1. WebIDE 편집기에서 TypeCheck.java 파일을 엽니다.

  2. main 메서드를 찾고 myAnimal에 대한 기존 검사 뒤에 다음 코드 줄을 추가합니다.

            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }

    완성된 TypeCheck.java 파일은 이제 다음과 같습니다.

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }
        }
    }
  3. 수정된 TypeCheck.java 파일을 저장합니다.

  4. 터미널에서 프로그램을 다시 컴파일합니다.

    javac TypeCheck.java
  5. 컴파일된 프로그램을 실행합니다.

    java TypeCheck

    이제 다음과 유사한 출력을 볼 수 있습니다.

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal

    이 출력은 Cat 객체를 포함하는 anotherAnimalCatAnimal의 인스턴스이지만 Dog의 인스턴스는 아님을 보여줍니다. 이는 instanceof가 객체의 실제 유형과 상속 계층 구조를 확인한다는 개념을 강화합니다.

다양한 하위 클래스 객체로 instanceof 키워드를 성공적으로 테스트했습니다. 다음 단계에서는 instanceofnull 객체에서 어떻게 동작하는지 살펴보겠습니다.

Null 객체 검증

이 마지막 단계에서는 테스트 중인 객체가 null일 때 instanceof 키워드가 어떻게 동작하는지 조사합니다. 이를 이해하는 것은 Java 프로그램에서 잠재적인 오류를 방지하는 데 중요합니다.

null 객체로 테스트를 포함하도록 TypeCheck.java 파일을 다시 수정합니다.

  1. WebIDE 편집기에서 TypeCheck.java 파일을 엽니다.

  2. 이전 테스트 후 main 메서드의 끝에 다음 코드 줄을 추가합니다.

            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }

    완성된 TypeCheck.java 파일은 이제 다음과 같습니다.

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is not an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is not an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }
        }
    }
  3. 수정된 TypeCheck.java 파일을 저장합니다.

  4. 터미널에서 프로그램을 컴파일합니다.

    javac TypeCheck.java
  5. 컴파일된 프로그램을 실행합니다.

    java TypeCheck

    다음과 유사한 출력을 볼 수 있습니다.

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal
    
    --- Testing with a null object ---
    nullAnimal is not an instance of Dog
    nullAnimal is not an instance of Animal

    출력에서 볼 수 있듯이 instanceof로 테스트 중인 객체가 null인 경우 결과는 항상 false입니다. 이는 예기치 않은 동작이나 NullPointerException을 방지하기 위해 instanceof를 사용할 때 기억해야 할 중요한 사항입니다.

instanceof 키워드가 null 객체에서 어떻게 동작하는지 성공적으로 확인했습니다. 이것으로 instanceof 키워드에 대한 탐구를 마칩니다.

요약

이 Lab 에서는 Java 에서 instanceof 키워드를 사용하여 객체가 특정 클래스의 인스턴스인지 또는 특정 인터페이스를 구현하는지 확인하는 방법을 배웠습니다. 기본 클래스와 하위 클래스를 사용하여 간단한 프로그램을 만들고, 런타임에 instanceof를 사용하여 객체의 유형을 확인하는 방식으로 사용법을 시연했습니다.

또한 instanceof가 하위 클래스에서 어떻게 동작하는지 탐구하여 객체가 자체 클래스뿐만 아니라 모든 상위 클래스의 인스턴스로 간주된다는 것을 확인했습니다. 마지막으로, null 객체에 적용될 때 instanceof의 동작을 검토하여 이러한 경우 항상 false를 반환한다는 것을 이해했습니다.