In Java, a class inherits one or more interfaces through the implements keyword. The methods defined by the interface must be implemented in the class: Define the interface: declare the method signature, but no specific implementation. Inherit an interface using implements: Inherit an interface using implements keyword and the interface name after the class name. Implement interface methods: Implement all methods declared in the inherited interface in the class. The method signature must exactly match the signature defined in the interface.
How to write class inheritance interface in Java
In Java, a class can use the implements keyword to inherit a or Multiple interfaces. Interfaces define a set of methods, but they do not provide implementations. The class must implement all methods declared in the inherited interface, otherwise compilation errors will occur.
Syntax:
<code class="java">public class <class_name> implements <interface_name> { // 类的方法实现 }</code>
Steps:
<code class="java">public interface <interface_name> { public void <method_name_1>(); public int <method_name_2>(); // 其他接口方法... }</code>
<code class="java">public class <class_name> implements <interface_name> { // 类的方法实现 }</code>
<code class="java">public class MyClass implements MyInterface { @Override public void myMethod1() { // 方法实现代码 } @Override public int myMethod2() { return 10; } }</code>
Example:
<code class="java">public interface Drawable { public void draw(); } public class Circle implements Drawable { @Override public void draw() { System.out.println("Drawing a circle..."); } }</code>
In this example, Circle The class implements the Drawable interface. It implements a method called draw() which prints a message indicating that it is drawing a circle.
The above is the detailed content of How to write class inheritance interface in java. For more information, please follow other related articles on the PHP Chinese website!