프로그래밍 언어/JAVA

업캐스팅과 instanceof 연산자

· 코딩마이데이

캐스팅(casting)이란 타입 변환을 말합니다. 클래스에 대한 캐스팅은 업캐스팅(upcasting)과 다운캐스팅(downcasting)으로 나뉩니다.

 

업캐스팅

서브 클래스는 슈퍼 클래스의 속성을 상속받기 때문에, 서브 클래스의 객체는 슈퍼 클래스의 멤버를 모두 가집니다. 그러므로 서브 클래스의 객체를 슈퍼 클래스의 객체로 취급할 수 있습니다.

서브 클래스의 객체에 대한 레퍼런스를 슈퍼 클래스 타입을 변환하는 것을 업캐스팅(upcasting)이라고 합니다.

업캐스팅은 슈퍼 클래스의 레퍼런스로 서브 클래스의 객체를 가리키게 합니다.

Person p;
Student s = new Student();
p = s; // 업캐스팅

 

이 코드에서, 슈퍼 클래스 타입의 레퍼런스 p가 서브 클래스 객체(s)를 가리키도록 치환되는 것이 업캐스팅입니다.

p.grade = "A"; // 컴파일 오류. grade는 Person의 멤버가 아님

 

업캐스팅한 레퍼런스는 객체 내에 모든 멤버에 접근할 수 없고 슈퍼 클래스의 멤버만 접근할 수 있습니다.

Student 객체가 Person 타입으로 업캐스팅되면, Person 타입의 객체로 취급되며 Student 클래스의 필드나 메소드는 접근할 수 없게 됩니다.

그리고 업캐스팅은 다음과 같이 명시적 타입 변환을 하지 않아도 됩니다. 그것은 Student 객체는 Person 타입이기도 하기 때문입니다.

p = (Person)s; // (Person)을 생략하고, p = s;로 해도 됨

 

업케스팅 사례

 

 

다운케스팅

업케스팅과 반대로 캐스팅하는 것을 다운캐스팅(downcasting)이라고 합니다.

Person p = new Student("채리"); // 업케스팅

 

다운 케스팅은 이와 반대로 Person 타입의 레퍼런스를 Student 타입의 레퍼런스로 변환하는 것으로, 다음과 같습니다.

Student s = (Student) p; // 다운 캐스팅, (Student)의 타입 변환을 반드시 표시

 

다운캐스팅은 업캐스팅과 달리 명시적으로 타입 변환을 지정해야 합니다.

다운캐스팅

 

업캐스팅과 instanceof 연산자

class Person {
	...
}
class Student extends Person {
	.....
}
class Researcher extends Person {
	.....
}
class Professor extends Researcher {
	.....
}

 

 

Person 클래스의 이를 상속받는 클래스들의 계층 관계

 

Person p = new Person();
Person p = new Student(); // 업캐스팅
Person p = new Researcher(); // 업캐스팅
Person p = new Professor(); // 업캐스팅
print(p);
void print(Person person) {
	// person이 가리키는 객체가 Person 타입일 수도 있고,
	// Student, Researcher, 혹은 Professor 타입일 수도 있다.
}

 

Person을 상속받은 객체업캐스팅되어 넘어왔다는 사실입니다.

 

instanceof 연산자 사용

레퍼런스가 가리키는 객체가 어떤 클래스 타입인지 구분하기 위해, 자바에서는 instanceof 연산자를 두고 있습니다.

레퍼런스 instanceof 클래스명

 

instanceof 연산자의 결과 값은 boolean 값으로, '레퍼런스'가 가리키는 객체가 해당 '클래스' 타입의 객체이면 true이고 false로 계산합니다.

Person jae = new Student();
Person kin = new Professor();
Person lee = new Researcher();
if (jae instanceof Person) // jae는 Person 타입이므로 true
if (jae instanceof Student) // jae는 Student 타입이므로 true
if (kim instanceof Student) // kim은 Student 타입이므로 false
if (kim instanceof Professor) // kim은 Professor 타입이므로 true
if (kim instanceof Researcher) // Professor 객체는 Researcher 타입이기도 하므로 true
if (lee instanceof Professor) // lee는 Professor 타입이 아니므로 false

 

instanceof는 클래스에만 적용되므로 다음은 오류입니다.

if (3 instanceof int) // 문법 오류. instanceofsms 객체에 대한 레퍼런스만 사용

 

다음은 instanceof 연산의 true입니다.

if ("java" instanceof String) // true

 

instanceof 연산자 활용

class Person { }
class Student extends Person { }
class Researcher extends Person { }
class Professor extends Researcher { }
public class InstanceOfEx {
    static void print(Person p) {
        if (p instanceof Person) {
            System.out.print("Person ");
        }
        if (p instanceof Student) {
            System.out.print("Student  ");
        }
        if (p instanceof Researcher) {
            System.out.print("Researcher ");
        }
        if (p instanceof Professor) {
            System.out.print("Professor ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        System.out.print("new Student() -> \t");
        print(new Student());
        System.out.print("new Research() -> \t");
        print(new Researcher());
        System.out.print("new Professor() -> \t");
        print(new Professor());
    }
}

 

실행 결과

new Student() ->  Person Student  
new Research() ->  Person Researcher 
new Professor() ->  Person Researcher Professor 

'프로그래밍 언어 > JAVA' 카테고리의 다른 글

추상 클래스  (0) 2025.02.13
메소드 오버라이딩  (0) 2025.02.10
상속과 생성자  (0) 2025.02.08
상속과 protected 접근 지정자  (0) 2025.02.07
클래스 상속과 객체  (1) 2025.02.06