서브 클래스의 객체는
- 슈퍼 클래스의 멤버를 모두 가지고 있음
- 슈퍼 클래스의 객체로 취급할 수 있음
업캐스팅
서브 클래스 객체를 슈퍼 클래스 타입으로 변환
class Person { … }
class Student extends Person { … }
Student s = new Student();
Person p = s; // 업캐스팅, 자동타입변환
업캐스팅된 레퍼런스는 객체 내의 슈퍼 클래스 멤버만 접근할 수 있음
다운캐스팅
슈퍼 클래스 객체를 서브 클래스 타입으로 변환
개발자의 명시적 타입 변환 필요
class Person { … }
class Student extends Person { … }
...
Person p = new Student("이재문"); // 업캐스팅
…
Student s = (Student)p; // 다운캐스팅, (Student)의 타입 변환 표시 필요
주로 한번 업캐스팅된 객체를 다시 다운캐스팅해주는 형태로 사용한다.
업캐스팅과 다운캐스팅을 하게 되면 그 레퍼런스의 객체가 원래 어떤 클래스의 객체였는지를 판단하기 어렵다.
Person p = new Person();
Person p = new Student(); // 업캐스팅
Person p = new Researcher(); // 업캐스팅
Person p = new Professor(); // 업캐스팅
void print(Person person) {
// person이 가리키는 객체가 Person 타입일 수도 있고,
// Student, Researcher, 혹은 Professor 타입일 수도 있다.
.....
}
intanceof 연산자를 사용하면 객체의 클래스 타입을 반환함
객체레퍼런스 instanceof 클래스타입
연산의 결과 : true/false의 불린 값
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 Professor()->\t"); print(new Professor());
}
}
상속 받은 타입에서 모두 true이므로
출력 :
new Professor -> Person Researcher Professor
'CS > JAVA' 카테고리의 다른 글
자바 - 추상클래스&인터페이스 (0) | 2022.04.21 |
---|---|
자바 - 오버로딩, 오버라이딩 (0) | 2022.04.20 |
자바 - 상속 (0) | 2022.04.10 |
자바 - static & final (0) | 2022.04.10 |
자바 - 접근 지정자 (0) | 2022.04.07 |