Java将父类转化为子类,编译没有报错,但是运行一直失败,可以帮忙讲解一下吗,感谢!
1/0也可以通过编译, 但是运行是不合逻辑的...
同样的, 转换类型这件事情, 语法上可以转的, 编译可以通过, 但是逻辑上不对的, 会抛错
爹会的事情, 儿子继承了必然会做; 因为继承的本质是一种扩展和增强, 儿子会做的事情, 爹不一定会做, 所以, 爹替代儿子去干活, 会出现问题
你的代码: son指向了old, (爹以儿子的名义去干活了, 有的功能不具备, 会出现问题)
所以, 第二张图中: 19行代码, 你检测一下
old instanceOf son1的返回结果是什么!
System.out.println(old instanceof son1);
结果肯定是false, 也就是说, 父类old对象并非是子类son1类的实例, 所以, 不能转换.
抛出的异常上也有明确注释: 不能转换为该子类的实例.
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
For example, the following code generates a ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);
Since:
1.0
Author:
unascribed