06. 업 캐스팅, 다운 캐스팅과 instanceof

0

Java 공부

목록 보기
6/18
post-thumbnail

다운 캐스팅(downcasting)

  • 자신의 고유한 특성을 잃은 서브 클래스의 객체를 다시 복구 시켜주는 것을 말한다. 그러니까 업캐스팅된 것을 다시 원상태로 돌리는 것을 말한다.
Customer vc = new VIPCustomer();              //묵시적
VIPCustomer vCustomer = (VIPCustomer)vc;      //명시적

업 캐스팅은 묵시적으로 사용 가능하지만
다운 캐스팅은 명시적으로 사용해야 한다.


class Mother{
	public void intro() {
		System.out.println("Mother");
	}
}
class Son extends Mother{
	public void intro() {
		System.out.println("Son");
	}
	public void say() {
		System.out.println("i love my mom");
	}
}

public class UpDownCasting {
	public static void main(String[] args) {
		
		Mother p1 = new Mother();
		Son p2 = new Son();
		
		//Up Casting
		Mother p3 = (Mother)p2;
		Mother p4 = p2; // 다형성으로 (Mother)생략가능
		p3.intro();
 //		p3.say(); // 사용불가 부모타입(Mother)은 say메서드가 없기 때문
	}
}
  • 구현되는 뒷부분 객체화되는 부분이 불러진다.
  • 즉, Mother p3는 옵션이고 뒤에 객체화된 p2가 Son이기 때문에
  • p3.intro(); 는 "Son" 이 출력된다.

에러 발생

Son p5 = p1; // 사용불가!!
// 다형성에서 앞에 자식이오고 뒤에 부모가 오는것은 불가능하다.
// 부모객체p1을 자식화 하기 위해 다운캐스팅이 필요하다.
Son p5 = (Son)p1; // 수정후.
p5.intro(); // 잘 작동하는지 확인해보자.

올바른 Down Casting 방법

// 올바른 Down Casting 방법
Son p5 = (Son)p3;
p5.intro();
  • p3는 타입은 Mother 이지만 객체화된 p2가 Son이다.
  • p3는 업 캐스팅되어 Son 객체화 된것이다.
  • Son p5 = (Son)p3; // Son의 p5와 Mother의 p3는 서로 다른타입 이기에 (Son)을 사용하여 다운캐스팅 진행!
  • p5.intro(); 와 p5.say(); 둘 다 사용가능하다.

instanceof를 이용하여 인스턴스의 형 체크

  • 원래 인스턴스의 형이 맞는지 여부를 체크하는 키워드 맞으면 true 아니면 false를 반환 함
VIPCustomer vc = (VIPCustomer)customerK;

에러 발생: customerK 는 GoldCustomer 인데 VIPCustomer로 캐스팅 할 수없음.

이 때 사용해볼 수 있는것이 instanceof 이다.

if (customerK instanceof VIPCustomer) { // customerK가 GoldCustomer인지 확인 시켜줘 => true값이면 아래코드 실행!!
			VIPCustomer vc = (VIPCustomer)customerK;
			System.out.println(customerK.showCustomerInfo());
		}

customerK 는 VIPCustomer 가 아니기 때문에 false를 반환한다.
콘솔창에 아무것도 나오지 않음.

if (customerK instanceof GoldCustomer) { // customerK가 GoldCustomer인지 확인 시켜줘 => true값이면 아래코드 실행!!
			GoldCustomer vc = (GoldCustomer)customerK;
			System.out.println(customerK.showCustomerInfo());
		}

customerK 는 GoldCustomer 가 아니기 때문에 true를 반환한다.
콘솔창: Kim님의 등급은 GOLD이며, 보너스 포인트는0입니다.

instanceof 를 통해 customerK 가 VIPCustomer인지 GoldCustomer인지 알 수 있다.

0개의 댓글