资讯专栏INFORMATION COLUMN

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

codercao / 2778人阅读

摘要:中的多态引用的多态父类的引用是可以指向子类对象报错方法多态动物具有吃的能力狗具有吃肉的能力狗具有看门的能力父类的引用是可以指向子类对象报错

java中的多态

引用的多态
/javaDemo4/src/com/imooc/Animal.java
package com.imooc;

public class Animal {
    
}
/javaDemo4/src/com/imooc/Dog.java
package com.imooc;

public class Dog extends Animal {

}
/javaDemo4/src/com/imooc/Initail.java
package com.imooc;

public class Initail {

    public static void main(String[] args) {

        Animal obj1 = new Animal();
        Animal obj2 = new Dog();  //父类的引用是可以指向子类对象
        //Dog obj3 = new Animal();  //报错


    }

}
方法多态
/javaDemo4/src/com/imooc/Animal.java
package com.imooc;

public class Animal {
    public void eat() {
        System.out.print("动物具有吃的能力");
    }
}
/javaDemo4/src/com/imooc/Dog.java
package com.imooc;

public class Dog extends Animal {
    public void eat() {
        System.out.print("狗具有吃肉的能力");
    }
    public void watchDoor() {
        System.out.print("狗具有看门的能力");
    }
}
/javaDemo4/src/com/imooc/Initail.java
package com.imooc;

public class Initail {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Animal obj1 = new Animal();
        Animal obj2 = new Dog();  //父类的引用是可以指向子类对象
        //Dog obj3 = new Animal();  //报错
        Animal obj3 = new Cat();
        obj1.eat();
        
        obj2.eat();
        obj3.eat();
//        obj2.watchDoor();
    }

}

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

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

相关文章

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

    摘要:多态中的引用类型转换代码自动类型提升,向上类型转换向下类型转换强制类型转型无法进行类型转换 多态中的引用类型转换 showImg(https://segmentfault.com/img/bVbnEal?w=1166&h=597); showImg(https://segmentfault.com/img/bVbnEaq?w=1178&h=606); 代码 /javaDemo4/src...

    gself 评论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条评论

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