소개
이 랩에서는 Java 에서 instanceof 키워드를 사용하여 객체가 특정 클래스 또는 인터페이스의 인스턴스인지 확인하는 방법을 배우게 됩니다. 기본 사용법을 살펴보고, 하위 클래스에서의 동작을 테스트하며, null 객체를 처리하는 방식을 이해할 것입니다.
실습 예제를 통해 런타임 타입 검사 (runtime type checking) 를 수행하기 위해 instanceof를 사용하는 실질적인 경험을 얻게 될 것입니다. 이는 객체 지향 프로그래밍의 기본적인 개념입니다.
instanceof 를 사용한 클래스 확인
이 단계에서는 Java 에서 instanceof 키워드를 살펴보겠습니다. instanceof 키워드는 객체가 특정 클래스의 인스턴스인지 또는 특정 인터페이스를 구현하는지 테스트하는 데 사용됩니다. 런타임에 객체의 타입을 확인하는 데 유용한 도구입니다.
instanceof가 어떻게 작동하는지 보여주는 간단한 Java 프로그램을 만들어 보겠습니다.
WebIDE 를 열고
~/project디렉토리에 있는지 확인합니다. 터미널 프롬프트를 보거나pwd를 입력하고 Enter 키를 눌러 확인할 수 있습니다.~/project디렉토리에TypeCheck.java라는 새 Java 파일을 만듭니다. 왼쪽의 파일 탐색기에서 마우스 오른쪽 버튼을 클릭하고 "New File"을 선택한 다음TypeCheck.java를 입력하여 이 작업을 수행할 수 있습니다.편집기에서
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과 두 개의 하위 클래스Dog및Cat을 정의합니다. main메서드에서Animal변수myAnimal을 생성하고Dog객체를 할당합니다.Dog는Animal의 한 유형이므로 가능합니다.- 그런 다음
instanceof키워드를 사용하여myAnimal이Dog,Cat및Animal의 인스턴스인지 확인합니다.
- 기본 클래스
TypeCheck.java파일을 저장합니다 (Ctrl+S 또는 Cmd+S).WebIDE 하단의 터미널을 열고 다음 명령을 실행하여 Java 프로그램을 컴파일합니다.
javac TypeCheck.java오류가 없으면 이 명령은
~/project디렉토리에TypeCheck.class,Animal.class,Dog.class및Cat.class파일을 생성합니다.다음 명령을 사용하여 컴파일된 프로그램을 실행합니다.
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 파일을 수정합니다.
WebIDE 편집기에서
TypeCheck.java파일을 엽니다.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"); } } }수정된
TypeCheck.java파일을 저장합니다.터미널에서 프로그램을 다시 컴파일합니다.
javac TypeCheck.java컴파일된 프로그램을 실행합니다.
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객체를 포함하는anotherAnimal이Cat및Animal의 인스턴스이지만Dog의 인스턴스는 아님을 보여줍니다. 이는instanceof가 객체의 실제 유형과 상속 계층 구조를 확인한다는 개념을 강화합니다.
다양한 하위 클래스 객체로 instanceof 키워드를 성공적으로 테스트했습니다. 다음 단계에서는 instanceof가 null 객체에서 어떻게 동작하는지 살펴보겠습니다.
Null 객체 검증
이 마지막 단계에서는 테스트 중인 객체가 null일 때 instanceof 키워드가 어떻게 동작하는지 조사합니다. 이를 이해하는 것은 Java 프로그램에서 잠재적인 오류를 방지하는 데 중요합니다.
null 객체로 테스트를 포함하도록 TypeCheck.java 파일을 다시 수정합니다.
WebIDE 편집기에서
TypeCheck.java파일을 엽니다.이전 테스트 후
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"); } } }수정된
TypeCheck.java파일을 저장합니다.터미널에서 프로그램을 컴파일합니다.
javac TypeCheck.java컴파일된 프로그램을 실행합니다.
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를 반환한다는 것을 이해했습니다.



