한모로그 2023. 1. 19. 20:53

instanceof 연산자

  • 매개변수가 아니더라도 변수가 참조하는 객체의 타입을 확인할 때 instanceof 연산자를 사용
  • instanceof 연산자에서 좌항의 객체가 우항의 타입이면 true를 산출하고 그렇지 않으면 false를 산출


    출처, 이것이 자바다


  • Java 12부터는 instanceof 연산의 결과가 true일 경우 우측 타입 변수를 사용할 수 있기 때문에 강제 타입 변환이 필요 없음
package ch07.sec09;

//부모클래스
public class Person {

    //필드 선언
    public String name;

    //생성자 선언. 컴파일 과정에서 기본생성자는 자동생성되지 않는다.
    public Person(String name) {
        this.name = name;
    }

//    public Person() {}

    //메소드 선언
    public void walk() {
        System.out.println("걷습니다.");
    }
}

package ch07.sec09;

//자식클래스
public class Student extends Person {

    //필드 선언
    public int studentNo;

    /*컴파일과정에서 아래 생성자가 자동생성된다.
     Student() {
         super();
     }
     */

    //생성자 선언
    public Student(String name, int studentNo) {
        super(name);
        this.studentNo = studentNo;
    }

    //메소드선언
    public void study() {
        System.out.println("공부를 합니다.");
    }
}

package ch07.sec09;

public class InstanceofExample {

    public static void personInfo(Person person) {
        System.out.println("name: " + person.name);
        person.walk();

        //person객체가 Student클래스 타입이냐?
        if(person instanceof Student) {
            Student student = (Student) person;
            System.out.println("studentNo: " + student.studentNo);
            student.study();
        }
    }
    //InstanceofExample 클래스의 종속된 구성멤버가 아니다. 일반메소드도 아니다. 독립적인 관점으로 본다. JVM소속
    public static void main(String[] args) {
        Person p1 = new Person("홍길동"); //Student 클래스와는 상관없이 독립적으로 객체생성
        personInfo(p1); // person instanceof Student : false

        System.out.println();

        Person p2 = new Student("이몽룡", 10); //힙영역에 Person클래스 메모리, Student클래스 메모리가 각각 생성
        personInfo(p2); // person instanceof Student : true
    }

}