1 package Demo512;
2
3 import com.sun.org.apache.xml.internal.serialize.Printer;
4
5 public class TestUsb {
6 public static void main(String[] args) {
7 Computer com= new Computer();
8 com.doWord(new printer());
9 com.doWord(new Flash());
10 // Flash f=new Flash();
11 // com.doWord(f);
12 //实现了接口的匿名类的对象
13 }
14 }
15 interface Usb{
16 void start();
17 void stop();
18 }
19 class Computer{
20 public void doWord(Usb usb){
21 usb.start();
22 System.out.println("==此设备开始操作==");
23 usb.stop();
24 }
25 }
26 class printer implements Usb{
27
28 @Override
29 public void start() {
30 System.out.println("打印机开始工作");
31 }
32
33 @Override
34 public void stop() {
35 System.out.println("打印机结束工作");
36 }
37 }
38 class Flash implements Usb{
39
40 @Override
41 public void start() {
42 System.out.println("u盘开始工作");
43 }
44
45 @Override
46 public void stop() {
47 System.out.println("u盘停止工作");
48 }
49 }
运行代码↓