업캐스팅
업캐스팅이란 서브클래스의 객체에 대한 래퍼런스를 슈퍼 클래스 타입으로 변환하는 것을 말한다.
업캐스팅한 래퍼런스로는 객체 내에 모든 멤버에 접근할 수 없고 슈퍼 클래스의 멤버만 접근할 수 있다.
class Person{
}
class Student extends Person{
}
public class UpcastingEx{
public static void main(String[] args){
Person p;
Student s;
p = s;
}
}
다운캐스팅
업캐스팅과 반대로 캐스팅하는 것을 다운캐스팅이라고 한다.
class Person{
String name;
String id;
public Person(String name){
this.name = name;
}
}
class Student extends Person{
String grade;
String department;
public Student(String name){
super(name);
}
}
public class ExtendsEx {
public static void main(String[] args) {
Person p = new Student("이재문");
Student s;
s= (Student)p;
System.out.println(s.name);
s.grade = "A";
}
}
위 코드처럼
Student s = (Student)p;
다운캐스팅은 업캐스팅과 달리 명시적 타입 변환을 지정해야 한다.
instance of
레퍼런스가 가리키는 객체가 어떤 클래스 타입인지 구분하기 위해, 자바에서는 instanceof 연산자를 두고 있다.
instanceof 연산자의 결과는 boolean 값으로, '레퍼런스'가 가리키는 객체가 해당 '클래스' 타입의 객체이면 true이고 아니면 false로 게산한다.
레퍼런스 instanceof 클래스명
instanceof는 클래스에만 적용되므로 다음은 오류이다.
if(3 instanceof int) //문법 오류, instanceof는 객체에 대한 레퍼런스만 사용
예제를 통해 더 알아보자.
class Person{
}
class Student extends Person{
}
class Researcher extends Person{
}
class Professor extends Reseracher{
}
위와 같은 상속 관계를 가진 클래스가 있다고 가정해보자.
Person jee = new Student();
Person Kim = new Professor();
Person lee = new Researcher();
if (jee instanceof Person) // ture
if (jee instanceof Student) // true
if (kim instanceof Student) // false
if (kim instanceof Professor) // true
if (kim instanceof Researcher) // true
if (lee instanceof Professor) // false
그럼 instanceof 연산은 위와 같은 결과가 나온다.
'2-1 학기 > OOP' 카테고리의 다른 글
[JAVA] Wrapper 클래스 (0) | 2023.05.31 |
---|---|
[JAVA] Object 클래스 (0) | 2023.05.31 |
[JAVA] 메소드 오버라이딩(Method Overriding) (0) | 2023.05.30 |
[JAVA] 추상 클래스 vs. 인터페이스 (0) | 2023.05.23 |
[JAVA] 상속 (0) | 2023.05.09 |