java如何写接口
Java 接口的基本语法
在 Java 中,接口通过 interface 关键字定义。接口可以包含抽象方法、默认方法、静态方法和常量。以下是接口的基本语法:
public interface MyInterface {
// 抽象方法(默认是 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 in interface");
}
// 常量(默认是 public static final)
String CONSTANT = "Interface Constant";
}
实现接口的类
类通过 implements 关键字实现接口,必须实现接口中的所有抽象方法(除非类是抽象的)。
public class MyClass implements MyInterface {
@Override
public void abstractMethod() {
System.out.println("Implemented abstract method");
}
}
接口的多重实现
Java 支持一个类实现多个接口,用逗号分隔接口名称。

public class MultiInterfaceImpl implements MyInterface, AnotherInterface {
@Override
public void abstractMethod() {
System.out.println("Implementation for MyInterface");
}
@Override
public void anotherMethod() {
System.out.println("Implementation for AnotherInterface");
}
}
接口的继承
接口可以通过 extends 关键字继承其他接口,支持多重继承。
public interface ParentInterface {
void parentMethod();
}
public interface ChildInterface extends ParentInterface {
void childMethod();
}
public class ChildImpl implements ChildInterface {
@Override
public void parentMethod() {
System.out.println("Parent method implementation");
}
@Override
public void childMethod() {
System.out.println("Child method implementation");
}
}
默认方法和静态方法
Java 8 引入了默认方法和静态方法,允许接口提供方法实现而不强制实现类重写。

public interface Calculator {
default int add(int a, int b) {
return a + b;
}
static int multiply(int a, int b) {
return a * b;
}
}
public class BasicCalculator implements Calculator {
// 可以直接使用默认方法
}
// 调用静态方法
int result = Calculator.multiply(3, 4);
函数式接口
如果一个接口只有一个抽象方法(可以有多个默认或静态方法),可以标记为 @FunctionalInterface,用于 Lambda 表达式。
@FunctionalInterface
public interface Greeting {
void greet(String name);
}
// 使用 Lambda 实现
Greeting greeting = (name) -> System.out.println("Hello, " + name);
greeting.greet("Alice");
接口与抽象类的区别
- 接口支持多重继承,抽象类不支持。
- 接口中的方法默认是抽象的(Java 8 前),抽象类可以包含具体方法。
- 接口中的成员变量默认是
public static final,抽象类没有此限制。
实际应用示例
以下是一个完整的接口定义和实现示例:
// 定义接口
public interface Vehicle {
void start();
void stop();
default void honk() {
System.out.println("Honking the horn");
}
}
// 实现接口
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
// 使用
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
car.start();
car.honk(); // 调用默认方法
car.stop();
}
}






