First, the concept of the interface
Interfaces are a more thorough abstraction. Interface is a specification abstracted from many similar classes, the interface does not provide any implementation, and the interface embodies the design philosophy of specification and realization separation.
Second, the definition of the interface
The interface definition no longer uses the class keyword, but instead uses the interface keyword.
The following is the basic syntax for defining an interface:
"Modifier" Interface interface name extends parent interface 1, parent interface 2 ...
{
Constant definition
Abstract method definition
}
- Modifiers can only be public or omitted, and omitted is the package access level, which means that the interface can be accessed only under the same package.
- An interface can have more than one parent class, but can only inherit and not implement an interface.
- The interface defines a common behavior specification for multiple classes, so the fields, methods, inner classes, and enumeration classes defined in the class are public access rights.
- The method in an interface can only be an abstract method, because abstract cannot be combined with static to decorate a method, so all methods in the interface are always public abstract to decorate, can default not write, by default will be added.
- The field defined in the interface is interface-dependent and can only be a constant, so the field defined in the interface is public static final decorated, which can be left default, and the system will add it.
- constructors and initialization blocks cannot be defined in an interface .
- An interface can define an inner class, an enumeration class, an interface, and the default is to use the public static adornment, and only the public static adornment.
Let's look at an example of an interface definition:
package Interfacedemo; public interface OutPut { // int max_cache_line = 50 // This sentence is equivalent to the above sentence // public static final int max_cache_line = 50; // void out (); void GetData (String msg);}
Third, the inheritance of the interface
Interfaces are not the same as classes, it supports multiple inheritance. Multiple parent interfaces are followed by the extends keyword, separated by commas. As with class inheritance, when an interface inherits a parent interface, it obtains all the abstract methods and constants defined in the parent interface.
Public InterfaceInterfacea {intA = 1; voidprint ();} Public InterfaceINTERFACEB {intB = 2; voidsay ();} Public InterfaceInterfacecextendsInterfacea, interfaceb{intC = 3; Public Static classTest { Public Static voidMain (string[] args) {System.out.println (INTERFACEC.A); System.out.println (INTERFACEC.B); System.out.println (INTERFACEC.C); } }}
The output is:
1
2
3
"JAVA" Interface (i)