java如何定义接口
定义接口的基本语法
在Java中,接口使用interface关键字定义。接口可以包含抽象方法、默认方法、静态方法和常量。定义接口的基本语法如下:
public interface InterfaceName {
// 常量(默认是public static final)
String CONSTANT = "value";
// 抽象方法(默认是public abstract)
void abstractMethod();
// 默认方法(Java 8引入)
default void defaultMethod() {
System.out.println("Default method implementation");
}
// 静态方法(Java 8引入)
static void staticMethod() {
System.out.println("Static method implementation");
}
}
接口中的抽象方法
接口中的抽象方法没有方法体,且默认是public abstract的。实现接口的类必须提供这些抽象方法的具体实现。
public interface Animal {
void eat();
void sleep();
}
接口中的默认方法
默认方法使用default关键字定义,允许在接口中提供方法的默认实现。实现类可以选择重写默认方法或直接使用默认实现。
public interface Vehicle {
default void start() {
System.out.println("Vehicle is starting");
}
}
接口中的静态方法
静态方法使用static关键字定义,属于接口本身,只能通过接口名调用,不能通过实现类的实例调用。

public interface MathOperations {
static int add(int a, int b) {
return a + b;
}
}
接口中的常量
接口中可以定义常量,常量默认是public static final的,必须初始化。
public interface Constants {
double PI = 3.14159;
String NAME = "Interface";
}
实现接口
类使用implements关键字实现接口,必须实现接口中的所有抽象方法(除非是抽象类)。
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}
多接口实现
一个类可以实现多个接口,用逗号分隔。

public class Car implements Vehicle, Engine {
@Override
public void start() {
System.out.println("Car is starting");
}
@Override
public void stop() {
System.out.println("Car is stopping");
}
}
接口继承
接口可以继承其他接口,使用extends关键字。一个接口可以继承多个接口。
public interface FlyingAnimal extends Animal, Flyable {
void fly();
}
函数式接口
函数式接口是只有一个抽象方法的接口,可以使用@FunctionalInterface注解标记。
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
}
标记接口
标记接口是没有定义任何方法的接口,仅用于标记类的特性。例如Serializable接口。
public interface Serializable {
// 无方法定义
}






