Detailed explanation of Java interface creation method and sample code
Abstract: This article will introduce the creation method of Java interface in detail and provide actual code examples to help readers better understand Understand and apply interface concepts.
1. What is an interface?
In object-oriented programming, an interface is an abstract data type that defines how a class should be implemented and used. An interface can contain definitions of constants and methods, but not instance fields. It provides a way to decouple classes from each other and make the interactions between classes more flexible and extensible.
2. Creation and Implementation of Interface
In Java, you can create an interface using the interface
keyword. The following is a simple interface example:
public interface Animal { String getSound(); void eat(); }
In the above example, we declare an interface named Animal
, which defines two abstract methods getSound()
and eat()
. The methods in the interface have no specific implementation, only the declaration of the method, and the specific implementation is provided by the class that implements the interface.
Interfaces are implemented by classes through the implements
keyword. Here is an example that implements the Animal
interface:
public class Dog implements Animal { @Override public String getSound() { return "汪汪汪"; } @Override public void eat() { System.out.println("狗在吃东西"); } }
In the above example, the Dog
class is implemented# by using the implements
keyword ##Animal interface, and provides specific implementations of the
getSound() and
eat() methods.
public interface Swim { void swim(); } public class Duck implements Animal, Swim { @Override public String getSound() { return "嘎嘎嘎"; } @Override public void eat() { System.out.println("鸭子在吃东西"); } @Override public void swim() { System.out.println("鸭子在游泳"); } }
Duck class implements both
Animal and
Swim interface and provides concrete implementations of all methods. In this way, the
Duck class can be used as either
Animal or
Swim.
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
The above is the detailed content of In-depth analysis of method creation and sample code of Java interface. For more information, please follow other related articles on the PHP Chinese website!