Creation method: 1. Define an interface named MyInterface and define an unimplemented method myMethod in it; 2. Create a class named MyClass and implement the MyInterface interface; 3. In the class, just implement the myMethod method in the interface.
Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Java, an interface is a reference type that defines a contract for a set of methods, but does not contain the implementation of the methods. A class can implement one or more interfaces. Implementing an interface requires that the method signature in the class exactly matches the method signature in the interface.
The following is an example of a simple Java interface creation:
java
// 定义一个接口 public interface MyInterface { // 定义一个没有实现的方法 void myMethod(); }
In the above code, we define an interface named MyInterface and define it in A method myMethod that is not implemented.
To implement this interface, we need to create a class and implement all the methods in the interface in the class. For example:
java
public class MyClass implements MyInterface { // 实现接口中的方法 @Override public void myMethod() { System.out.println("实现了MyInterface接口的myMethod方法"); } }
In the above code, we created a class named MyClass and implemented the MyInterface interface. In the class, we implement the myMethod method in the interface. Note that the @Override annotation is added before the method signature, which helps the compiler check the correctness of the method.
The above is the detailed content of How to create a java interface. For more information, please follow other related articles on the PHP Chinese website!