Upcasting & Downcasting
class Unit { public void attack() { System.out.println("유닛 공격"); } } class Zealot extends Unit { public void attack() { System.out.println("찌르기"); } public void teleportation() { System.out.println("프로토스 워프"); } } public class Main { public static void main(String[] args) { Unit unit_up; Zealot zealot = new Zealot(); // * 업캐스팅(upcasting) unit_up = (Unit) zealot; unit_up = zealot; // 업캐스팅은 형변환 괄호 생략 가능 } }Unit unit = new Unit(); // * 다운캐스팅(downcasting) 예외 - 다운캐스팅은 업스캐팅한 객체를 되돌릴때 적용 되는것이지, 오리지날 부모 객체를 자식 객체로 강제 형변환은 불가능 Zealot unit_down2 = (Zealot) unit; //! RUNTIME ERROR - Unit cannot be cast to Zealot unit_down2.attack(); //! RUNTIME ERROR unit_down2.teleportation(); //! RUNTIME ERROR
Last updated