在Java中,接口是一种定义类应遵循的规范或行为的方式。以下是创建和使用接口的基本步骤:
定义接口
使用`interface`关键字来定义接口。接口可以包含抽象方法和常量。
public interface Animal {void eat();void sleep();}
实现接口
使用`implements`关键字在类中实现接口,并提供接口中所有方法的具体实现。
public class Cat implements Animal {@Overridepublic void eat() {System.out.println("Cat is eating");}@Overridepublic void sleep() {System.out.println("Cat is sleeping");}}
接口中的方法
接口中的方法默认是`public`和`abstract`的,不需要显式声明。
接口中的常量
接口中可以声明`public static final`常量,但不允许声明实例变量。
接口的继承
接口可以继承其他接口,使用`extends`关键字。

public interface Flyable {void fly();}public interface Swimmable {void swim();}public interface Animal extends Flyable, Swimmable {// Animal接口继承了Flyable和Swimmable接口}
接口的实现类
实现类必须实现接口中的所有方法。
public class Bird implements Animal {@Overridepublic void eat() {System.out.println("Bird is eating seeds");}@Overridepublic void sleep() {System.out.println("Bird is sleeping on branch");}@Overridepublic void fly() {System.out.println("Bird is flying");}@Overridepublic void swim() {System.out.println("Bird is swimming");}}
接口提供了一种定义类之间契约的方式,实现了接口的类必须遵循接口定义的行为。这有助于实现代码的重用性、解耦和松散耦合
