How to define interfaces in Java
In Java, the interface keyword can be used to define an interface. An interface specifies a set of method specifications but does not include the implementation of the methods. Below is a simple example of an interface definition.
public interface MyInterface {
void method1();
int method2(String str);
}
In interfaces, you can define the signature of methods (method name and parameter list), but you cannot include the implementation of the methods. The methods in an interface are by default public and abstract, and these two keywords can be omitted.
In addition to defining methods, interfaces can also define constants. The constants in an interface are by default public, static, and final, and these keywords can be omitted. For example:
public interface MyInterface {
int MAX_COUNT = 100;
// ...
}
An interface can be implemented by a class (using the “implements” keyword), and a class can implement multiple interfaces. The class implementing an interface must implement all the methods in the interface. For example:
public class MyClass implements MyInterface {
@Override
public void method1() {
// 实现method1的逻辑
}
@Override
public int method2(String str) {
// 实现method2的逻辑
return 0;
}
}
Interfaces can also inherit from other interfaces using the keyword “extends”. For example:
public interface MyInterface2 extends MyInterface {
void method3();
}
The above is the method of defining interfaces in Java. Interfaces provide a way to separate method specifications and implementations, making code more extensible and flexible.