抽象类和接口-开发打印机案例

 1 package com.ketang.print;
 2 
 3 /**
 4  * 纸张接口
 5  * @author 
 6  *
 7  */
 8 public interface Paper {
 9     String getSize();
10 }
 1 package com.ketang.print;
 2 
 3 /**
 4  * A4纸张
 5  * @author 
 6  *
 7  */
 8 public class A4Paper  implements Paper{
 9 
10     public String getSize() {
11         return "A4";
12     }
13     
14 }
 1 package com.ketang.print;
 2 
 3 /**
 4  * B5纸张
 5  * @author 
 6  *
 7  */
 8 public class B5Paper implements Paper {
 9 
10     public String getSize() {
11         return "B5";
12     }
13 }
 1 package com.ketang.print;
 2 /**
 3  * 墨盒接口
 4  * @author 
 5  *
 6  */
 7 public interface InkBox {
 8     
 9     //获得颜色
10     String getColor();
11 }
 1 package com.ketang.print;
 2 
 3 /**
 4  * 彩色墨盒
 5  * @author 
 6  *
 7  */
 8 public class ColorInkBox implements InkBox {
 9 
10     public String getColor() {
11         return "彩色";
12     }
13     
14 }
 1 package com.ketang.print;
 2 
 3 /**
 4  * 黑白墨盒
 5  * @author 
 6  *
 7  */
 8 public class GrayInkBox implements InkBox {
 9 
10     public String getColor() {
11         return "黑白";
12     }
13     
14 }
 1 package com.ketang.print;
 2 
 3 /**
 4  * 打印机
 5  * @author 
 6  *
 7  */
 8 public class Printer {
 9     InkBox inkBox;
10     Paper paper;
11     
12     public InkBox getInkBox() {
13         return inkBox;
14     }
15 
16     public void setInkBox(InkBox inkBox) {
17         this.inkBox = inkBox;
18     }
19 
20     public Paper getPaper() {
21         return paper;
22     }
23     
24     public void setPaper(Paper paper) {
25         this.paper = paper;
26     }
27 
28     public void print() {
29         System.out.println("你使用的是"+inkBox.getColor()+"墨盒和"+paper.getSize()+"纸张打印");
30     }
31 
32 }
 1 package com.ketang.print;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         Printer printer=new Printer();
 7 
 8         printer.setInkBox(new ColorInkBox());
 9         printer.setPaper(new A4Paper());
10         printer.print();
11         
12         printer.setInkBox(new GrayInkBox());
13         printer.setPaper(new B5Paper());
14         printer.print();
15 
16     }
17 
18 }

猜你喜欢

转载自www.cnblogs.com/baichang/p/10067673.html