1. Requirements:
1. Set up a USB interface on the computer.
2. When the computer is running, connect the mouse to the interface, and the mouse can use its own functions.
3. When the computer is running, connect the keyboard to the interface, and the keyboard can use its own functions.
(The role of using the interface: reduce the coupling between peripheral devices such as mouse and keyboard and the notebook computer. It can also increase the expandability of the computer.)
2. Example code:
1 // Design, define USB interface rules 2 interface USB 3 { 4 /** 5 Run device 6 */ 7 public void open(); 8 } 9 10 // Describe computer 11 class computer 12 { 13 /** 14 computer run 15 */ 16 public void run() 17 { 18 System.out.println("computer ......" ); 19 } 20 21 /** 22 Use a peripheral device that conforms to the rules 23 */ 24 public void useUSB(USB usb) // Define a reference to an interface type. 25 { 26 if (usb != null ); 27 { 28 usb.open(); 29 } 30 } 31 } 32 33 class Mouse 34 { 35 public void run() 36 { 37 System.out.println("Mouse . ....." ); 38 } 39 } 40 41 class Keyboard 42 { 43 public void run() 44 { 45 System.out.println("Keyboard ......" ); 46 } 47 } 48 49 /** 50 A compatible USB interface is connected mouse. 51 */ 52 class MouseUSB extends Mouse implements USB 53 { 54 public void open() 55 { 56 System.out.println("Mouse USB open ......" ); 57 } 58 } 59 60 /** 61 A USB-compliant keyboard is connected. 62 */ 63 class KeyboardUSB extends Keyboard implements USB 64 { 65 public void open() 66 { 67 System.out.println("Keyboard USB open ..." ); 68 } 69 } 70 71 /** 72 Something that conforms to the USB interface is connected. 73 */ 74 class ThingUSB implements USB 75 { 76 public void open() 77 { 78 System.out.println("open ..." ); 79 } 80 } 81 82 class USBTest 83 { 84 public static void main(String[ ] arge) 85 { 86 /** 87 computer c starts running 88 */ 89 computer c = new computer(); 90 c.run(); 91 92 /** 93 Connect the mouse m to the interface useUSB, the mouse can use its own functions 94 */ 95 MouseUSB m = new MouseUSB(); 96 c.useUSB(m); 97 m. run(); 98 99 /** 100 Connect the keyboard k to the interface useUSB, the keyboard can use its own functions 101 */ 102 KeyboardUSB k = new KeyboardUSB(); 103 c.useUSB(k); 104 k.run( ); 105 106 /** 107 something connected to the interface useUSB, can use 108 */ 109 USB t = new ThingUSB(); // Polymorphism. Can be connected to the interface can be used. 110 c.useUSB(t); 111 } 112 }
Third, the code runs: