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); //
    给猫喂鱼


        }
    }
  • 相关阅读:
    IE 11 使用 flexbox 垂直居中 bug
    Electron build 无法下载 winCodeSign 等资源
    Electron 开发环境下总是 crash
    解决 Electron 包下载太慢问题
    Netty--数据通信和心跳检测
    Netty编解码技术和UDP实现
    Netty入门
    Java 网络IO编程(BIO、NIO、AIO)
    java.util.concurrent常用类(CountDownLatch,Semaphore,CyclicBarrier,Future)
    JDK多任务执行框架(Executor框架)
  • 原文地址:https://www.cnblogs.com/willpower/p/1249882.html
Copyright © 2011-2022 走看看