资讯专栏INFORMATION COLUMN

java入门第二季--多态--多态中的引用类型转换

gself / 737人阅读

摘要:多态中的引用类型转换代码自动类型提升,向上类型转换向下类型转换强制类型转型无法进行类型转换

多态中的引用类型转换

代码

</>复制代码

  1. /javaDemo4/src/com/imooc/Animal.java

</>复制代码

  1. package com.imooc;
  2. public class Animal {
  3. }

</>复制代码

  1. /javaDemo4/src/com/imooc/Dog.java

</>复制代码

  1. package com.imooc;
  2. public class Dog extends Animal {
  3. }

</>复制代码

  1. /javaDemo4/src/com/imooc/Cat.java

</>复制代码

  1. package com.imooc;
  2. public class Cat extends Animal {
  3. }

</>复制代码

  1. Initail.java

</>复制代码

  1. package com.imooc;
  2. public class Initail {
  3. public static void main(String[] args) {
  4. Dog dog = new Dog();
  5. Animal animal = dog; //自动类型提升,向上类型转换
  6. Dog dog2 = (Dog)animal; //向下类型转换 强制类型转型
  7. if(animal instanceof Cat) {
  8. Cat cat = (Cat)animal;
  9. }else {
  10. System.out.println("无法进行类型转换");
  11. }
  12. }
  13. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73145.html

相关文章

  • java门第二季--多态--java中的多态

    摘要:中的多态引用的多态父类的引用是可以指向子类对象报错方法多态动物具有吃的能力狗具有吃肉的能力狗具有看门的能力父类的引用是可以指向子类对象报错 java中的多态 showImg(https://segmentfault.com/img/bVbnDYA?w=1138&h=612); showImg(https://segmentfault.com/img/bVbnD6B?w=344&h=17...

    codercao 评论0 收藏0
  • java门第二季--多态--java中的接口

    摘要:中的接口实例智能手机和都有玩游戏的功能代码具有玩游玩的功能具有玩游玩的功能 java中的接口 showImg(https://segmentfault.com/img/bVbnEzV?w=1194&h=621); showImg(https://segmentfault.com/img/bVbnEzX?w=1192&h=615); showImg(https://segmentfaul...

    Doyle 评论0 收藏0
  • java门第二季--多态--java中的抽象类

    摘要:中的抽象类代码实现通过键盘来打电话通过键盘来打短信通过语音来打电话通过语音来发短信运行 java中的抽象类 showImg(https://segmentfault.com/img/bVbnEiG?w=1189&h=613); showImg(https://segmentfault.com/img/bVbnEiH?w=1214&h=620); showImg(https://segm...

    hosition 评论0 收藏0
  • java门第二季--继承--java中的继承初始化顺序

    摘要:中的继承初始化顺序父类和子类年龄动物可以吃东西类执行了年龄狗可以吃东西类执行了对象的属性和构造方法年龄动物可以吃东西类执行了的 java中的继承初始化顺序 showImg(https://segmentfault.com/img/bVbnBI1?w=1277&h=671); showImg(https://segmentfault.com/img/bVbnBKG?w=811&h=427...

    CoorChice 评论0 收藏0
  • java门第二季--继承--java中的方法重写

    java中的方法重写 showImg(https://segmentfault.com/img/bVbnBEj?w=1260&h=668); 重写前 showImg(https://segmentfault.com/img/bVbnBEu?w=347&h=158); /javaDemo3/src/com/imooc/Animal.java package com.imooc; public cl...

    Cc_2011 评论0 收藏0

发表评论

0条评论

gself

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<