Java - 상속 받은 객체 타입 변환 (Up-Casting / Down-Casting)

반응형

업캐스팅(Up-Casting)

  • 클래스들간의 다양성을 구성하는데 사용
  • 상속 받은 객체의 타입을 변경하기 위해 사용
  • 데이터 타입은 상위 클래스이나 하위 클래스의 재정의 된 메서드 실행
  • 데이터 타입이 상위 클래스이므로 상위 클래스에 정의된 변수만 사용 가능
  • 업캐스팅 정의는 상위클래스 객체이름 = new 하위클래스();
  • 업캐스팅 된 객체는 다운캐스팅 가능
  • 상속 관계의 클래스에서만 업/다운 캐스팅 가능

 

업캐스팅 예시

  • 상위 클래스로 선언하였지만 객체 생성은 하위 클래스
  • 상위 클래스이지만 실행되는 메소드는 하위 클래스의 메소드
package Casting;

// 상위 클래스 (= 부모 클래스)
public class UpCastingParent {
	protected int x, y;
	
	public UpCastingParent() {
		x = 10;
		y = 20;
	}
	
	public int add() {
		System.out.println("Parent add()");
		return x + y ;
	}
}

// 하위 클래스 (= 자식 클래스)
public class UpCastingChild extends UpCastingParent {
	private int z;
	
	public UpCastingChild() {
		x = 100;
		y = 200;
		z = 300;
	}
	
	@Override
	public int add() {
		System.out.println("Child add()");
		return x + y + z;
	}
}

// 메인 클래스
public class UpCastingMain {
	public static void main(String[] args) {
		System.out.println("UpCastingParent obj");
		UpCastingParent up = new UpCastingParent(); // 부모클래스 객체 생성
		System.out.println("up.add() = " + up.add()); // up.add() = 30

		System.out.println("UpCastingChild obj");
		UpCastingChild uc = new UpCastingChild(); // 자식클래스 객체 생성
		System.out.println("uc.add() = " + uc.add()); // uc.add() = 600
		
		System.out.println("UpCasted obj");
		UpCastingParent upc = new UpCastingChild(); // 업캐스팅 객체 생성
		System.out.println("upc.add() = " + upc.add()); // upc.add() = 600
		// upc 객체를 부모클래스(UpCastingParent)로 선언
		// upc 객체를 자식클래스(UpCastingChild)로 생성
		// 겉모습은 부모클래스이지만 메소드는 자식 클래스의 메소드 실행
	}
}

 

업캐스팅 된 객체 upc의 추가 설명

  • 값이 600이 출력되는 이유는?
    • 상위 클래스 형태이지만 업캐스팅되었기 때문에 하위 클래스의 메소드 실행 (x+y+z)
  • z는 하위 클래스의 변수라서 사용이 불가한데 z의 값 300을 포함하여 결과가 600이 나오는 이유는?
    • 하위 클래스 호출시 생성자에 의해 x(100), y(200), z(300)의 값이 설정되었기 때문
      • upc.x 의 값은 100임을 확인 할 수 있음
      • upc.z의 값은 업캐스팅 된 객체기 때문에 값이 존재하지 않음 > 에러 출력

다운캐스팅(Down-Casting)

  • 업캐스팅 된 객체를 다시 되돌리는 것

 

다운캐스팅 예시

  • 출력의 "Hello! Bye!" 는 업캐스팅 된 객체이므로 자식 클래스의 메소드 실행
  • "Hi~" 는 다운캐스팅되어 자식 클래스 자신의 메소드 실행
package Casting;

// 부모 클래스
public class DownCastingParent {
	protected String msg = "Hello!";
	
	public void Msg() {
		System.out.print(msg);
	}
}

// 자식 클래스
public class DownCastingChild extends DownCastingParent {
	@Override
	public void Msg() {
		super.Msg();
		System.out.print("Bye!");
	}
	public void AddMsg() {
		System.out.print("Hi~");
	}
}

// 다운캐스팅 클래스
public class DownCastingAction {
	public void action(DownCastingParent dp) { // 파라미터에서 업 캐스팅
		dp.Msg();
		if (dp instanceof DownCastingChild) { // 객체 타입 비교
			( (DownCastingChild) dp ).AddMsg(); // 다운캐스팅
		}
	}
}

// 매인 클래스
public class DownCastingMain {

	public static void main(String[] args) {
		DownCastingAction da = new DownCastingAction();
		DownCastingChild dc = new DownCastingChild();
		da.action(dc); // Hello! Bye! Hi~
	}
}
반응형