Java面向對象之多態實例2
轉載于 : http://www.verejava.com/?id=16992846385655
創新互聯公司從2013年開始,先為磴口等服務建站,磴口等地企業,進行企業商務咨詢服務。為磴口企業網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
/** 題目: 孩子吃 水果(蘋果,葡萄,芒果,菠蘿) 思路: 1. 抽象出類 : 孩子(Baby), 水果(Fruit)(蘋果(Apple),葡萄(Grape),芒果(Mango)) 2. 找出類的關系: 水果 -> 孩子 (蘋果,葡萄,芒果) 是 水果的分類 3. 找出屬性: 孩子(姓名,水果引用) 4. 找出方法: 孩子吃(eat)水果 子類->父類的轉換 作用 :解耦 也就是降低類與類之間的耦合度 提供可擴展性 */public class Polymorphism3 { public static void main(String[] args) { //實例化一個Baby Baby baby = new Baby("李明"); //實例化一個蘋果 和 一個葡萄 Apple apple = new Apple("紅富士"); Grape grape = new Grape("黑葡萄"); Mango mango = new Mango("大芒果"); PineApple pineApple = new PineApple("菠蘿"); //李明吃蘋果 baby.eat(apple); System.out.println(baby.getName() + " 吃了 " + baby.getFruit().getName()); baby.eat(grape); System.out.println(baby.getName() + " 吃了 " + baby.getFruit().getName()); baby.eat(mango); System.out.println(baby.getName() + " 吃了 " + baby.getFruit().getName()); baby.eat(pineApple); System.out.println(baby.getName() + " 吃了 " + baby.getFruit().getName()); } }class Baby { private Fruit fruit; private String name; public Baby(String name) { this.name = name; } public String getName() { return this.name; } public Fruit getFruit() { return this.fruit; } //吃水果 public void eat(Fruit fruit) { this.fruit = fruit; } }class Fruit { private String name; public Fruit(String name) { this.name = name; } public String getName() { return this.name; } }class PineApple extends Fruit { public PineApple(String name) { super(name); } }class Apple extends Fruit { public Apple(String name) { super(name); } }class Grape extends Fruit { public Grape(String name) { super(name); } }class Mango extends Fruit { public Mango(String name) { super(name); } }
轉載于 : http://www.verejava.com/?id=16992846385655
當前標題:Java面向對象之多態實例2
分享路徑:http://www.xueling.net.cn/article/pgeccd.html