In Java, an interface is an abstract type that defines a set of abstract methods and constants (or no methods or constants). An interface is a convention that specifies the behavior that a certain type of object should have.
Here is some important information about Java interfaces:
-
Define interface :
Use
interface
the keyword to define the interface.interface MyInterface { // 声明抽象方法 void myMethod(); // 声明常量(默认为 public static final) int MY_CONSTANT = 10; }
-
Implement interface :
A class can implement one or more interfaces,
implements
implemented through the keyword.class MyClass implements MyInterface { @Override public void myMethod() { System.out.println("Implementing myMethod"); } }
-
The difference between interface and abstract class :
- Methods in interfaces are abstract by default and do not contain method bodies; abstract classes can contain abstract methods and concrete methods.
- A class can implement multiple interfaces, but can only inherit from one class.
- The fields in the interface are of
public static final
type by default, that is, constants; abstract classes can contain fields of various types.
-
Multiple inheritance of interfaces :
An interface can inherit from multiple interfaces.
interface InterfaceA { void methodA(); } interface InterfaceB { void methodB(); } interface InterfaceC extends InterfaceA, InterfaceB { void methodC(); }
-
Default method :
Java 8 introduced default methods of interfaces, which can provide default implementations of methods in interfaces.
interface MyInterface { void myMethod(); default void defaultMethod() { System.out.println("Default method implementation"); } }
-
Static method :
Java 8 also introduced static methods in interfaces.
interface MyInterface { void myMethod(); static void staticMethod() { System.out.println("Static method in interface"); } }
-
Practical applications of the interface :
- Interfaces are used to implement polymorphism, which allows different classes to have the same behavioral interface, but in different implementation methods.
- An interface is a design convention used to describe what methods and constants a class should have.
- The Java standard library uses interfaces extensively, such as
java.util.List
interfaces.
Interface is a very important concept in Java. It provides a way to organize and standardize the structure of code, and supports more flexible polymorphism.