强转一定要注意:
对象的真实类型是什么,那么强转最小只能转换为此类型。
首先,我们来看一段代码:
/**
* @author: tpp
* @version: 1.0
* @description: Cast.java
* @date: 2021/3/17 18:09
*/
public class Cast extends Super_Cast2{
public static void main(String[] args) {
// TODO Auto-generated method stub
Super_Cast2 s2 = new Super_Cast2();
Super_Cast1 s1 = s2;
System.out.println(s2);
Cast cast = (Cast)s1;
}
@Override
public void check() {
// TODO Auto-generated method stub
System.out.println("Cast");
}
}
class Super_Cast1{
public void check() {
System.out.println("Super_Cast1");
}
}
class Super_Cast2 extends Super_Cast1{
public void check() {
System.out.println("Super_Cast2");
}
}
解:我们来分析一下代码,Cast继承Super_Cast2,Super_Cast2继承Super_Cast1,即Super_Cast1>Super_Cast2>Cast。因为一个子对象可以被当作一个父类类型,所以s1=s2这个是多态的向上转型。而Cast cast = (Cast)s1 是强制转换,即把s1祖先强制转换成Cast类型,这个操作是否成功呢?让我们来编译一下,看看结果:
tpp.Super_Cast2@15db9742
Exception in thread "main" java.lang.ClassCastException: tpp.Super_Cast2 cannot be cast to tpp.Cast
at tpp.Cast.main(Cast.java:10)
显然,这是不行的,为什么呢?首先我们看Super_Cast2 s2 = new Super_Cast2()这一段代码,这一句代表着Super_Cast2创建了s2对象。但是多态语法中有一个注意事项,那就是:对象的真实类型是什么,那么强转最小只能转换为此类型,所以Super_Cast2类就是最小类型。但因为Super_Cast2类是Cast类的父类,所以由s2向上转型的s1就不能强转为cast。
解决办法:
把代码中的Super_Cast2 s2 = new Super_Cast2()改为Super_Cast2 s2 = new Cast()。
public class Cast extends Super_Cast2{
public static void main(String[] args) {
// TODO Auto-generated method stub
Super_Cast2 s2 = new Cast();
Super_Cast1 s1 = s2;
System.out.println(s2);
Cast cast = (Cast)s1;
}
@Override
public void check() {
// TODO Auto-generated method stub
System.out.println("Cast");
}
}
class Super_Cast1{
public void check() {
System.out.println("Super_Cast1");
}
}
class Super_Cast2 extends Super_Cast1{
public void check() {
System.out.println("Super_Cast2");
}
}
结果:
tpp.Cast@15db9742
解析:
因为现在是Super_Cast2 s2 = new Cast(),代表着s2所能强转的最小类型是Cast,由s2向上转型的s1就可以强转为cast。
希望可以和大家互相学习,谢谢大家!!!