zoukankan      html  css  js  c++  java
  • 多态用法 由于动物很多,所以创建一个人类来喂动物

     1 package cn.zmh.A;
     2 
     3 //动物类
     4 public class Animal {
     5    void eat(){
     6        
     7    }
     8 }
     9 
    10 //猫类
    11  class Cat extends Animal {
    12     void eat(){
    13         System.out.println("猫吃鱼");
    14     }
    15 }
    16  
    17  //狗类
    18  class Dog extends Animal {
    19         void eat(){
    20             System.out.println("狗吃骨头");
    21         }
    22     }
    23 
    24 //人类   喂猫喂狗
    25  class Persosn extends Animal {
    26         void feedAnimal(Animal anim){
    27 
    28            //打印运行的地址
    29             anim.eat();
    30         }
    31     }
    32  
    33 //测试类
    34  class TestAnimal {
    35 
    36 
    37         public static void main(String[] args){
    38            //多态写法
    39            Animal d = new Dog();
    40            Animal c = new Cat();
    41             
    42             Persosn p = new Persosn();
    43             
    44             //子类的值d赋值给父类Animal
    45             Animal aimn = (Animal) d;
    46             p.feedAnimal(aimn);
    47             
    48             //子类的值c赋值给父类Animal
    49             Animal aimn1 = (Animal) c;
    50             p.feedAnimal(aimn1);
    51             
    52         }
    53     }
  • 相关阅读:
    爬取网页图片
    python 猜数字游戏
    位移运算
    生成随机的名字
    不截半个汉字
    一致性hash的实现
    安装前端脚手架
    什么是快速排序?
    HTML5有趣的标签
    stopPropagation / stopImmediatePropagation
  • 原文地址:https://www.cnblogs.com/zhangmenghui/p/10544786.html
Copyright © 2011-2022 走看看