您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

无法在运行时在Java中向下转换

无法在运行时在Java中向下转换

动物不可能是狗,也可能是猫,或者像您这样的动物

Animal a= new Animal(); // a points in heap to Animal object
Dog dog = (Dog)a; // A dog is an animal but not all animals are  dog

对于垂头丧气,您必须执行此操作

Animal a = new Dog();
Dog dog = (Dog)a;

顺便说一句,垂头丧气是危险的,您可以使用它RuntimeException,如果出于培训目的也可以。

如果要避免运行时异常,可以执行此检查,但是会慢一些。

 Animal a = new Dog();
 Dog dog = null;
  if(a instanceof Dog){
    dog = (Dog)a;
  }
java 2022/1/1 18:28:53 有525人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶