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     }
  • 相关阅读:
    spring core与context的理解
    maven项目中pom.xml快速生成
    MariaDB常用命令
    MariaDB快速入门指南
    My_plan_51
    Oracle简介及安装
    Oracle单行函数
    oracle多表查询
    单点登录原理与简单实现
    JavaScript 的时间消耗
  • 原文地址:https://www.cnblogs.com/zhangmenghui/p/10544786.html
Copyright © 2011-2022 走看看