在程序中,我将父类的对象强制转换为子类的对象,为什么会报错?既然是强制转换,本来就是从大类型到小类型的转换啊???
package com.imooc;
//学习多态
public class Initial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog = new Dog();
Animal animal = dog;//自动类型提升 向上类型转换
Animal animal2 = new Animal();
Dog dog2 = (Dog)animal2;//向下类型转换 强制类型转换
// Cat cat = (Cat)animal;
}
}
运行结果:
Exception in thread "main" java.lang.ClassCastException: com.imooc.Animal cannot be cast to com.imooc.Dog
at com.imooc.Initial.main(Initial.java:22)不是你这个意思的,它原来是一只动物,你没说它是什么动物就强行转换成一只狗可以么?不可以!
但是 如果 它原来就是一只狗的话
Animal animal = new Dog();
Dog dog2 = (Dog)animal;
这样就不会报错了。
Animal animal = new Dog();和 Dog animal = new Dog();除了不能引用子类独有的方法外,有区别吗? Animal animal = new Dog();到底是怎样的意思?
任何时候,将父类对象强制转换为子类对象,编译都能通过。这句话对吗?