一个例子体现面向对象编程好处.doc
上传人:qw****27 上传时间:2024-09-12 格式:DOC 页数:4 大小:21KB 金币:15 举报 版权申诉
预览加载中,请您耐心等待几秒...

一个例子体现面向对象编程好处.doc

一个例子体现面向对象编程好处.doc

预览

在线预览结束,喜欢就下载吧,查找使用更方便

15 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

1.一个饲养员给动物喂食物的例子体现JAVA中的面向对象思想,接口(抽象类)的用处packagecom.softeem.demo;/***@authorleno*动物的接口*/interfaceAnimal{publicvoideat(Foodfood);}/***@authorleno*一种动物类:猫*/classCatimplementsAnimal{publicvoideat(Foodfood){System.out.println("小猫吃"+food.getName());}}/***@authorleno*一种动物类:狗*/classDogimplementsAnimal{publicvoideat(Foodfood){System.out.println("小狗啃"+food.getName());}}/***@authorleno*食物抽象类*/abstractclassFood{protectedStringname;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}}/***@authorleno*一种食物类:鱼*/classFishextendsFood{publicFish(Stringname){this.name=name;}}/***@authorleno*一种食物类:骨头*/classBoneextendsFood{publicBone(Stringname){this.name=name;}}/***@authorleno*饲养员类**/classFeeder{/***饲养员给某种动物喂某种食物*@paramanimal*@paramfood*/publicvoidfeed(Animalanimal,Foodfood){animal.eat(food);}}/***@authorleno*测试饲养员给动物喂食物*/publicclassTestFeeder{publicstaticvoidmain(String[]args){Feederfeeder=newFeeder();Animalanimal=newDog();Foodfood=newBone("肉骨头");feeder.feed(animal,food);//给狗喂肉骨头animal=newCat();food=newFish("鱼");feeder.feed(animal,food);//给猫喂鱼}}