zoukankan      html  css  js  c++  java
  • 体现JAVA中的面向对象思想,接口(抽象类)的用处 :饲养员给动物喂食物


    package com.softeem.demo;

    /**
    *@authorleno
    *
    动物的接口
    */
    interface Animal
    {
        publicvoid eat(Food food);
    }
    /**
    *@authorleno
    *
    一种动物类:
    */
    class Cat implements Animal
    {
        publicvoid eat(Food food)
        {
          System.out.println("
    小猫吃"+food.getName());
        }
    }
    /**
    *@authorleno
    *
    一种动物类:
    */
    class Dog implements Animal
    {
        publicvoid eat(Food food)
        {
          System.out.println("
    小狗啃"+food.getName());
        }
    }

    /**
    *@authorleno
    *
    食物抽象类
    */
    abstractclass Food
    {
        protected String name;
        public String getName() {
          returnname;
        }

        publicvoid setName(String name) {
          this.name = name;
        }
    }

    /**
    *@authorleno
    *
    一种食物类:
    */
    class Fish extends Food
    {
        public Fish(String name) {
          this.name = name;
        }
    }
    /**
    *@authorleno
    *
    一种食物类:骨头
    */
    class Bone extends Food

        public Bone(String name) {
          this.name = name;
        }
    }

    /**
    *@authorleno
    *
    饲养员类
    *
    */
    class Feeder
    {
        /**
        *
    饲养员给某种动物喂某种食物
        *@paramanimal
        *@paramfood
        */
        publicvoid feed(Animal animal,Food food)
        {
          animal.eat(food);
        }
    }

    /**
    *@authorleno
    *
    测试饲养员给动物喂食物
    */
    publicclass TestFeeder {

        publicstaticvoid main(String[] args) {
          Feeder feeder=new Feeder();
          Animal animal=new Dog();
          Food food=new Bone("
    肉骨头");
          feeder.feed(animal,food); //
    给狗喂肉骨头
          animal=new Cat();
          food=new Fish("
    ");
          feeder.feed(animal,food); //
    给猫喂鱼


        }
    }
  • 相关阅读:
    P4178 Tree
    CF437D The Child and Zoo
    CF1032G Chattering ST表+倍增
    P4165 [SCOI2007]组队 推柿子+差分
    P1450 [HAOI2008]硬币购物 容斥原理+完全背包
    P6275 [USACO20OPEN]Sprinklers 2: Return of the Alfalfa P 轮廓线DP
    P6009 [USACO20JAN]Non-Decreasing Subsequences P 矩阵优化DP
    P2605 [ZJOI2010]基站选址 线段树优化DP
    P5597 【XR-4】复读 思维题 +二叉树合并
    P5304 [GXOI/GZOI2019]旅行者 最短路+位运算优化
  • 原文地址:https://www.cnblogs.com/willpower/p/1249882.html
Copyright © 2011-2022 走看看