package com.webex.async.steps.copy.test;
class ParentDemo {
}
class SunDemo extends ParentDemo {
}
class X extends SunDemo {
}
class Y extends ParentDemo {
}
public class Copy_2_of_Sun {
public static void main(String[] args) {
ParentDemo x = new X();
SunDemo sun = (SunDemo) x;
//Exception in thread "main" java.lang.ClassCastException: com.webex.async.steps.copy.test.Y cannot be cast to com.webex.async.steps.copy.test.SunDemo
//at com.webex.async.steps.copy.test.Copy_2_of_Sun.main(Copy_2_of_Sun.java:27)
ParentDemo Y = new Y();
sun = (SunDemo) Y;
}
class ParentDemo {
}
class SunDemo extends ParentDemo {
}
class X extends SunDemo {
}
class Y extends ParentDemo {
}
public class Copy_2_of_Sun {
public static void main(String[] args) {
ParentDemo x = new X();
SunDemo sun = (SunDemo) x;
//Exception in thread "main" java.lang.ClassCastException: com.webex.async.steps.copy.test.Y cannot be cast to com.webex.async.steps.copy.test.SunDemo
//at com.webex.async.steps.copy.test.Copy_2_of_Sun.main(Copy_2_of_Sun.java:27)
ParentDemo Y = new Y();
sun = (SunDemo) Y;
}
}
从2个名词开始说起:向上转型(upcasting) 、向下转型(downcasting).
举个例子:有2个类,Father是父类,Son类继承自Father。
Father f1 = new Son(); // 这就叫 upcasting (向上转型)
// 现在f1引用指向一个Son对象
Son s1 = (Son)f1; // 这就叫 downcasting (向下转型)
// 现在f1还是指向Son对象
第2个例子:
Father f2 = new Father();
Son s2 = (Son)f2; // 出错,子类引用不能指向父类对象
你或许会问,第1个例子中:Son s1 = (Son)f1;问什么 是正确的呢。
很简单因为f1指向一个子类对象,Father f1 = new Son(); 子类s1引用当然可以指向子类对象了。
而f2 被传给了一个Father对象,Father f2 = new Father();子类s1引用不能指向父类对象。