1. What is an interface
In life, interfaces are a set of specifications that meet the specifications of a device that can be assembled together to enable the device to function
2. Attention Points of the interface
01. Interfaces cannot be instantiated because interfaces are more abstract than abstract classes
21 Classes If you implement an interface, you must override all of the methods in that interface
03. Interfaces cannot be constructed, but abstract classes can have
04. Abstract methods that all methods in the interface are public
05. All fields in the interface must be public static constants
06. The interface itself is also a data type
07. The interface simply defines the specification for the class that implements it, ensuring that the implementation class method signature is consistent with the corresponding method in the interface.
08. Multiple inheritance can be achieved through the interface
09. An excuse is best to define only one method to prevent contamination of the interface
3. The difference between abstract classes and interfaces
01. There can be ordinary methods in the abstract class, the interface cannot
02. Abstract classes can have constructs, interfaces cannot
03. Abstract classes can have normal fields, but not in the interface
04. Abstract classes cannot implement multiple inheritance, and interfaces can
05. The selected abstract class in accordance with the is a relationship, in accordance with the selected interface of the has a relationship
05. Interfaces are more abstract than abstract classes
Let's look at an example to understand the interface
01 A USB port
Package CN. Day001; /** */Publicinterface usbinterface {/** * USB Interface provides service * /void service ();}
USB Interface for 02.U disk
Package CN. Day001; // USB Stick Public class Implements Usbinterface { publicvoid service () { // Implement USB interface System.out.println ("Connect USB port, start transmitting data");} }
USB Interface for 03.U disk
Package CN. Day001; // USB Fan Public class Implements usbinterface { // Implement Interface public void service () { System.out.println ("Connect the USB port, get the current, the fan starts to turn");} }
04. Test Class
package CN. Day001; // test class, implemented using public class Test { public static void main (string[] args) {// 1.u disk usbinterface Udisk=new Udisk (); Udisk.service (); // 2.usb fan usbinterface ufan=< Span style= "color: #0000ff;" >new Usbfan (); Ufan.service (); }}
Test results:
Interfaces in Java