1 package com.szxs.goods;2 /**3 * 父类:商品类4 * @author 5 *6 */7 public abstract class Goods {8 public abstract void printPrice();9 }
1 package com.szxs.goods; 2 3 //食品类 4 public class Foods extends Goods { 5 6 public void printPrice() { 7 System.out.println("食品的价格是10元"); 8 9 }10 11 }
1 package com.szxs.goods; 2 /** 3 * 电视类 4 * @author 5 * 6 */ 7 public class TVs extends Goods { 8 9 public void printPrice() {10 System.out.println("电视的价格是4998元");11 12 }13 14 }
1 package com.szxs.goods; 2 /** 3 * 商场类 4 * @author 5 * 6 */ 7 public class Mark { 8 public Goods buy(int type) { 9 Goods goods=null;10 switch(type) {11 case 1:12 return goods=new Foods(); 13 case 2:14 return goods=new TVs();15 }16 return goods;17 18 }19 }
1 package com.szxs.goods; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 Mark m=new Mark(); 7 m.buy(1).printPrice(); 8 } 9 10 }