[SEB BE] Section 1. 다형성(polymorphism) - instanceof 연산자, 다형성의 활용

박두팔이·2022년 12월 30일
0

자바

목록 보기
13/26

instanceof 연산자

instanceof 연산자는 상속관계에 있는 참조변수의 타입변환(캐스팅)이 가능한지의 여부를 boolean타입으로 확인할 수 있는 자바문법이다.

💡 캐스팅가능여부를 판단하는 두 가지 기준이 있다.

  • 객체를 어떤 생성자로 만들었나
  • 클래스 사이에 상속관계가 존재하는지

// 기본문법
(인스턴스참조변수 instanceof 검사할타입);

// 예시
System.out.println(animal instanceof Animal);

코드를 살펴보자. 먼저 4개의 클래스가 있고 메인메서드가 실행되는 클래스, super클래스, sub클래스Bat과 Cat이 있다.

class Cat은 Animal클래스를 상속(extends)받는 서브클래스다.

Animal클래스타입의 animal인스턴스를 만든 뒤, 두 관계가 과연 형변환이 가능한지의 여부를 알아보는 코드이다.

결과는 true/false로 나타나며 상속관계에서만 이루어질 수 있다.

public class InstanceOfExample {
    public static void main(String[] args) {
        Animal animal = new Animal();
        System.out.println(animal instanceof Object); //true
        System.out.println(animal instanceof Animal); //true
        System.out.println(animal instanceof Bat); //false
        
	  	Animal cat = new Cat();
        System.out.println(cat instanceof Object); //true
        System.out.println(cat instanceof Animal); //true
        System.out.println(cat instanceof Cat); //true
        System.out.println(cat instanceof Bat); //false
    }
}

class Animal {};
class Bat extends Animal{};
class Cat extends Animal{};        

Cat 객체를 예로 들어보면, 생성된 객체는 Animal 타입으로 선언되어있지만 다형적 표현 방법에 따라 Object와 Animal 타입으로도 선언될 수 있다는 점을 확인할 수 있다.

profile
기억을 위한 기록 :>

0개의 댓글