본문 바로가기
Programming/Java

5장. 상속 #2 업/다운캐스팅

by jaegom 2020. 6. 11.

업다운캐스팅

업캐스팅(upcasting) : 서브클래스 객체를 슈퍼클래스 타입으로 변환
ex)
class Person {}
class Student extends Person {}
Person p = new Student(); 업캐스팅

cf)

Student s = new Student();
Person p = s; 레퍼런스만 치환해주면 됨.
업캐스팅된 s는 슈퍼클래스의 멤버만 접근 가능하다.

 

2. 다운캐스팅(downcasting) : 슈퍼클래스 객체를 서브클래스 타입으로 변환


ex)
class Person{}
class Student extends Person{}
Person p = new Person();
Student s = (Student)p; //캐스팅 필요

3. instanceof 연산자 - if문과 같이 쓴다

-상속받은 클래스는 타입 판단이 어려움 -> instanceof 연산자 활용
ex)
s intanceof Student >>> True

p instanceof Person >>> False

댓글