Java父类强制转换子类原则

  1. public class TestObjectConvert {

  2.    public static void main(String[] args) {

  3.        test1();

  4.        test2();

  5.    }

  6.    private static void test1() {

  7.        Fruit fruit1 = new Fruit();

  8.        Apple apple1 = new Apple();

  9.        apple1 = (Apple) fruit1; // java.lang.ClassCastException

  10.    }

  11.    private static void test2() {

  12.        Fruit fruit1 = new Apple();

  13.        Apple apple1 = new Apple();

  14.        apple1 = (Apple) fruit1;

  15.    }

  16.    static class Fruit {

  17.    }

  18.    static class Apple extends Fruit {

  19.    }

  20. }

结果是:

 
  1. test1:报类转异常;

  2. test2:转换正常。

所以,想让父类强制转换成子类,不是没有可能,除非父类是子类构造出来的实例,不然是不能强转的。

为什么呢?

如上代码,如果父类实例出来的对象是Orange,Orange当然不能强制转成Apple,所以说父类只有该子类对应的实例才能强转。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值