Chapter 7、面向对象(四)--- 多态
接口
1 package org.hanqi.pn0120; 2 3 public class Computer 4 { 5 //品牌 6 private String brand; 7 //CPU 8 private ICPU cpu; 9 //显卡 10 private IDisplayCard displaycard; 11 12 13 public String getBrand() { 14 return brand; 15 } 16 public void setBrand(String brand) { 17 this.brand = brand; 18 } 19 public ICPU getCpu() { 20 return cpu; 21 } 22 public void setCpu(ICPU cpu) { 23 this.cpu = cpu; 24 } 25 public IDisplayCard getDisplaycard() { 26 return displaycard; 27 } 28 public void setDisplaycard(IDisplayCard displaycard) { 29 this.displaycard = displaycard; 30 } 31 32 //运行 33 public void run() 34 { 35 this.cpu.command(); 36 this.displaycard.display(); 37 System.out.println("我组装的"+brand+"电脑开始运行"); 38 } 39 40 public Computer(String brand) { 41 super(); 42 this.brand = brand; 43 } 44 45 public static void main(String []args) 46 { 47 //组装电脑 48 Computer c1=new Computer("hp"); 49 50 //第一种:匿名类 new AMD() 51 c1.setCpu(new AMD()); 52 //第二种: 53 AMD a1=new AMD(); 54 c1.setCpu(a1); 55 56 c1.setDisplaycard(new Nivida()); 57 58 c1.run(); 59 60 61 Computer c2=new Computer("ASUS"); 62 c2.setCpu(new Intel()); 63 c2.setDisplaycard(new Ati()); 64 c2.run(); 65 System.out.println("------------------"); 66 67 AMD2 a2=new AMD2(); 68 Computer c3=new Computer("acer"); 69 c3.setCpu(a2); 70 c3.setDisplaycard(a2); 71 c3.run(); 72 System.out.println("------------------"); 73 74 AMD3 a3=new AMD3(); 75 Computer c4=new Computer("acer"); 76 c4.setCpu(a3); 77 c4.setDisplaycard(a3); 78 c4.run(); 79 } 80 81 }
1 package org.hanqi.pn0120; 2 //CPU接口 3 public interface ICPU 4 { 5 //控制 6 public void command(); 7 }
1 package org.hanqi.pn0120; 2 //显卡接口 3 public interface IDisplayCard 4 { 5 //显示 6 public void display(); 7 8 }
1 package org.hanqi.pn0120; 2 3 public class Intel implements ICPU { 4 5 @Override 6 public void command() 7 { 8 System.out.println("我是Interl的CPU"); 9 10 } 11 12 }
1 package org.hanqi.pn0120; 2 3 public class AMD implements ICPU 4 { 5 6 @Override 7 public void command() 8 { 9 System.out.println("我是AMD的CPU"); 10 11 } 12 13 }
1 package org.hanqi.pn0120; 2 3 public class Nivida implements IDisplayCard { 4 5 @Override 6 public void display() 7 { 8 System.out.println("我是N显卡"); 9 10 } 11 12 }
1 package org.hanqi.pn0120; 2 3 public class Ati implements IDisplayCard { 4 5 @Override 6 public void display() 7 { 8 System.out.println("我是A显卡"); 9 10 } 11 12 }
1 package org.hanqi.pn0120; 2 3 public class AMD2 implements ICPU, IDisplayCard { 4 5 @Override 6 public void display() 7 { 8 System.out.println("AMD的CPU显卡"); 9 10 } 11 12 @Override 13 public void command() 14 { 15 System.out.println("AMD自带显卡的CPU"); 16 17 } 18 19 }
1 package org.hanqi.pn0120; 2 3 public class AMD3 extends AMD implements IDisplayCard { 4 5 @Override 6 public void display() { 7 // TODO 自动生成的方法存根 8 System.out.println("继承了AMD一代的CPU,增加了显卡功能"); 9 10 } 11 12 }