728x90
형 변환(업캐스팅)
상위 클래스로 변수를 선언하고 하위 클래스의 생성자로 인스턴스를 생성
상속 관계에서 모든 하위 클래스는 상위 클래스로 형 변환(업캐스팅)이 됨 (그 역은 성립하지 않음)
형 변환과 메모리
Customer vc = new VIPCustomer();
VIPCustomer()생성자에 의해 VIPCustomer클래스의 모든 멤버 변수에 대한 메모리는 생성되었지만,
변수의 타입이 Customer이므로
실제 접근 가능한 변수나 메서드는 Customer의 변수와 메서드이다.
다운캐스팅
- 업캐스팅된 클래스를 다시 원래의 타입으로 형 변환
- 하위 클래스로의 형 변환은 명시적으로 해야 함
if ( customerE instanceof GoldCustomer ) {
GoldCustomer vc = (GoldCustomer)customer;
System.out.println(customerE.showCustomerInfo());
}
instanceof = 왼쪽 인스턴스가 오른쪽 인스턴스 였는지
public void testDownCasting(ArrayList<Animal> list) {
for (int i = 0; i<list.size(); i++) {
Animal animal = list.get(i);
if(animal instanceof human) {
Human human = (human)animal;
}
}
}
코드가 지저분해질 수 있다.
굳이 원래 인스턴스로 돌아가야 한다면 instanceof로 사용
728x90
댓글