Interfaceusb{voidstart (); voidstop ();}classc{ Public Static voidWork (USB u) {u.start (); System.out.println ("In Work"); U.stop (); }}classUsbdiskImplementsusb{@Override Public voidstart () {System.out.println ("U disk starts to work"); } @Override Public voidStop () {System.out.println ("USB Stick Stops working"); } }classPrinterImplementsusb{@Override Public voidstart () {System.out.println ("Printer started working"); } @Override Public voidStop () {System.out.println ("Printer stopped working"); } } Public classAbsDemo01 { Public Static voidMain (string[] args) { c.work ( new Usbdisk ()); C.work (New Printer ()); } }
Analysis:
1. In the interface, there are two abstract methods, void Start () and void Stop (). In fact, in these two abstract methods, the preceding public abstract is omitted.
2. In Class C, a work class method is created. In the main () method, C.word (New Usbdisk ()) and C.word (New Printer ()) are used. In this case, we use the class name. Method name to invoke the method, using the Static keyword knowledge. A class that uses static adornments is called a class method, which can be called directly by the class name or by an instance object. (It is recommended to call directly with the class name, since the steps instantiated with new can be omitted directly, more concise and more convenient)
3. In the main () method,c.work (new Usbdisk) uses the knowledge of the parent class declaration and subclass instantiation when transferring parameters. We can understand it this way:USB u = new Usbdisk, the declaration part is an interface, the assignment part is the object u that implements the class, and the method of invoking the implementation class when invoking the overridden abstract method .
Java notes (4) interface