Java 에서 객체가 특정 유형인지 확인하는 방법

JavaBeginner
지금 연습하기

소개

이 랩에서는 Java 에서 instanceof 연산자를 사용하여 객체가 특정 유형인지 확인하는 방법을 배우게 됩니다. 먼저 상속을 포함하여 다양한 클래스에서 instanceof의 기본 사용법을 이해하는 것으로 시작합니다.

그런 다음 다양한 클래스 유형으로 instanceof 연산자를 테스트하고, 하위 클래스와 상위 클래스에서 어떻게 동작하는지 살펴봅니다. 마지막으로, 잠재적인 오류를 방지하기 위해 instanceof를 사용할 때 null 객체를 처리하는 방법을 배우게 됩니다.

instanceof 연산자 사용

이 단계에서는 Java 의 instanceof 연산자에 대해 배우게 됩니다. instanceof 연산자는 객체가 특정 클래스의 인스턴스인지 또는 특정 인터페이스를 구현하는지 테스트하는 데 사용됩니다. 런타임에 객체의 유형을 확인하는 데 유용한 도구입니다.

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

  1. WebIDE 편집기에서 HelloJava.java 파일을 엽니다 (아직 열려 있지 않은 경우).

  2. 파일의 전체 내용을 다음 코드로 바꿉니다.

    class Animal {
        public void makeSound() {
            System.out.println("Generic animal sound");
        }
    }
    
    class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof!");
        }
    }
    
    class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow!");
        }
    }
    
    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            }
        }
    }

    이 코드에서:

    • 기본 클래스 Animal과 두 개의 하위 클래스 DogCat을 정의합니다.
    • main 메서드에서 Animal 변수 myAnimal을 생성하고 Dog 객체를 할당합니다.
    • 그런 다음 instanceof 연산자를 사용하여 myAnimalDog, CatAnimal의 인스턴스인지 확인합니다.
  3. 파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

  4. 터미널에서 javac 명령을 사용하여 프로그램을 컴파일합니다.

    javac HelloJava.java
  5. java 명령을 사용하여 컴파일된 프로그램을 실행합니다.

    java HelloJava

    어떤 instanceof 검사가 true 를 반환했는지 나타내는 출력을 볼 수 있습니다.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal

    보시다시피, myAnimalDog의 인스턴스입니다 ( Dog 객체를 생성했기 때문) 그리고 Animal의 인스턴스이기도 합니다 ( DogAnimal의 하위 클래스이기 때문). Cat의 인스턴스는 아닙니다.

다양한 클래스로 테스트

이전 단계에서 instanceof가 하위 클래스와 상위 클래스에서 어떻게 작동하는지 확인했습니다. 이제 서로 관련이 없는 다른 클래스를 대상으로 테스트할 때 어떻게 동작하는지 살펴보겠습니다.

기존 HelloJava.java 파일을 수정하여 다른 클래스를 포함하고 instanceof 연산자를 다른 유형의 객체로 테스트합니다.

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

  2. Car라는 새 클래스를 파일에 추가합니다. 이 클래스 정의는 Animal, Dog, Cat 클래스 앞이나 뒤에 추가할 수 있지만, HelloJava 클래스 외부에 있어야 합니다.

    class Car {
        public void drive() {
            System.out.println("Driving a car");
        }
    }
  3. 이제 HelloJava 클래스 내의 main 메서드를 수정하여 Car 객체를 생성하고 instanceof 연산자를 테스트해 보겠습니다. main 메서드를 다음과 같이 업데이트합니다.

    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
            Car myCar = new Car();
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            }
    
            System.out.println("--- Testing Car object ---");
    
            if (myCar instanceof Car) {
                System.out.println("myCar is an instance of Car");
            }
    
            if (myCar instanceof Animal) {
                System.out.println("myCar is an instance of Animal");
            }
        }
    }

    새로운 Car 객체 myCar를 추가하고 CarAnimal에 대한 instanceof 검사를 포함했습니다.

  4. 파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

  5. 수정된 프로그램을 컴파일합니다.

    javac HelloJava.java
  6. 프로그램을 실행합니다.

    java HelloJava

    출력을 관찰합니다. 이전 단계의 결과와 함께 Car 객체에 대한 새로운 검사 결과가 표시되어야 합니다.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal
    --- Testing Car object ---
    myCar is an instance of Car

    이 출력은 myCarCar의 인스턴스임을 확인하지만, CarAnimal에서 상속되지 않으므로 Animal의 인스턴스는 아닙니다. instanceof 연산자는 객체와 클래스 간의 유형 관계 (또는 관계 부재) 를 올바르게 식별합니다.

Null 객체 처리

이 마지막 단계에서는 null 객체를 처리할 때 instanceof 연산자가 어떻게 동작하는지 살펴보겠습니다. 이를 이해하는 것은 프로그램에서 예기치 않은 오류를 방지하는 데 중요합니다.

Java 에서 null 참조는 변수가 어떤 객체도 참조하지 않음을 의미합니다. null 참조와 함께 instanceof 연산자를 사용하면 항상 false를 반환합니다. 이것은 연산자의 내장된 안전 기능입니다.

HelloJava.java 파일을 마지막으로 수정하여 null 객체를 포함하고 instanceof 연산자를 테스트해 보겠습니다.

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

  2. HelloJava 클래스 내의 main 메서드를 수정하여 null Animal 참조를 포함하고 테스트합니다. main 메서드를 다음과 같이 업데이트합니다.

    class Animal {
        public void makeSound() {
            System.out.println("Generic animal sound");
        }
    }
    
    class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof!");
        }
    }
    
    class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow!");
        }
    }
    
    class Car {
        public void drive() {
            System.out.println("Driving a car");
        }
    }
    
    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
            Car myCar = new Car();
            Animal nullAnimal = null; // Declare a null Animal reference
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            }
    
            System.out.println("--- Testing Car object ---");
    
            if (myCar instanceof Car) {
                System.out.println("myCar is an instance of Car");
            }
    
            if (myCar instanceof Animal) {
                System.out.println("myCar is an instance of Animal");
            }
    
            System.out.println("--- Testing null object ---");
    
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            }
    
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            }
        }
    }

    새로운 Animal 변수 nullAnimal을 추가하고 null로 초기화했습니다. 그런 다음 이에 대해 instanceof 검사를 수행합니다.

  3. 파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

  4. 프로그램을 컴파일합니다.

    javac HelloJava.java
  5. 프로그램을 실행합니다.

    java HelloJava

    출력을 관찰합니다. 이전 단계의 결과와 함께 nullAnimal에 대한 검사 결과가 표시되어야 합니다.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal
    --- Testing Car object ---
    myCar is an instance of Car
    --- Testing null object ---

    nullAnimal에 대한 if 블록 내부의 줄이 인쇄되지 않는 것을 확인합니다. 이는 nullAnimal instanceof AnimalnullAnimal instanceof Dog가 모두 false로 평가되기 때문입니다. 이는 instanceof 연산자가 false를 반환하여 null 참조를 올바르게 처리함을 보여줍니다.

instanceofnull과 어떻게 작동하는지 이해하는 것은 NullPointerException 오류를 방지하는 강력한 Java 코드를 작성하는 데 중요합니다.

요약

이 랩에서는 instanceof 연산자를 사용하여 Java 에서 객체가 특정 유형인지 확인하는 방법을 배웠습니다. 객체의 런타임 유형을 결정하기 위해 기본 클래스와 하위 클래스를 포함한 다양한 클래스와 함께 instanceof를 사용하는 연습을 했습니다. 또한 객체의 실제 클래스, 상위 클래스 및 관련 없는 클래스를 대상으로 검사할 때 instanceof가 어떻게 동작하는지 살펴보았습니다.