public class TestPerson {
public static void main(String[] args) {
// 向上类型转换,正常运行
Animal a = new Cat();
a.show();
// 向下类型转换,正常运行
Animal cat = new Cat();
Cat cat2 = (Cat) cat;
cat2.show();
// 运行时异常
Cat cat3 = (Cat) new Animal();
cat3.show();
// 正常运行
Cat cat4 = (Cat) getAnimal(a);
cat4.show();
// 运行异常
Cat cat5 = (Cat) getAnimal();
cat4.show();
}
public static Animal getAnimal(Animal a) {
return a;
}
public static Animal getAnimal() {
return new Animal();
}
}
class Animal {
public void show() {
System.out.println("Animal");
}
}
class Cat extends Animal {
public void show() {
System.out.println("Cat");
}
}我的疑惑是:明明都是强制转换,为什么有的会报异常,有的却可以正常进行?主要是异常的部分。
注:我能理解向上类型转换以及向下类型转换正常运行的代码,只是不理解那些异常的代码。
请大神讲解,感激不尽
qq_阳光下的海风_0
dky
qq_碎流_0
qq_碎流_0
scala_somnus_gxy
随时随地看视频慕课网APP
相关分类