1 public class TestUSB {
2 public static void main(String[] args) {
3 Computer com = new Computer();
4 com.doWork(new Printer());
5
6 Flash f = new Flash();
7 com.doWork(f);
8
9 //实现接口的匿名类的对象
10 USB phone = new USB(){
11 @Override
12 public void start() {
13 System.out.println("手机开始工作");
14 }
15 @Override
16 public void stop() {
17 System.out.println("手机停止连接");
18 }
19
20 };
21 com.doWork(phone);
22
23
24 //实现接口的匿名类的对象
25 com.doWork(new USB(){
26 @Override
27 public void start() {
28 System.out.println("手机开始工作");
29 }
30 @Override
31 public void stop() {
32 System.out.println("手机停止连接");
33 }
34 });
35 }
36 }
37
38 class Computer{
39 public void doWork(USB usb){
40 usb.start();
41 System.out.println("。。。此设备开始操作。。。");
42 usb.stop();
43 }
44 }
45
46 interface USB{
47 //USB的尺寸的大小,可以设置为常量
48
49 //功能设置为抽象方法
50 void start();
51 void stop();
52 }
53 //打印机
54 class Printer implements USB{
55 public void start(){
56 System.out.println("打印机开始工作");
57 }
58 public void stop(){
59 System.out.println("打印机停止工作");
60 }
61 }
62 //U盘
63 class Flash implements USB{
64 public void start(){
65 System.out.println("U盘开始工作");
66 }
67 public void stop(){
68 System.out.println("U盘停止工作");
69 }
70 }