java如何提供接口
Java接口的定义与实现
在Java中,接口(Interface)是一种完全抽象的类,用于定义一组方法规范而不提供具体实现。接口通过interface关键字声明,类通过implements关键字实现接口。
// 定义接口
interface Animal {
void eat();
void sleep();
}
// 实现接口
class Dog implements Animal {
public void eat() {
System.out.println("Dog is eating");
}
public void sleep() {
System.out.println("Dog is sleeping");
}
}
默认方法与静态方法
Java 8之后,接口可以包含默认方法(default修饰)和静态方法(static修饰),允许在接口中提供部分实现逻辑。

interface Vehicle {
void start();
default void stop() {
System.out.println("Vehicle stopped");
}
static void honk() {
System.out.println("Honk!");
}
}
接口的多重实现
Java支持类实现多个接口,解决了单继承的限制。多个接口用逗号分隔。

interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flying");
}
public void swim() {
System.out.println("Duck swimming");
}
}
接口继承
接口可以通过extends关键字继承其他接口,形成接口层次结构。
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
class C implements B {
public void methodA() {}
public void methodB() {}
}
函数式接口
Java 8引入函数式接口(@FunctionalInterface),仅包含一个抽象方法,常用于Lambda表达式。
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
// 使用Lambda实现
Calculator add = (a, b) -> a + b;
System.out.println(add.calculate(2, 3)); // 输出5
接口与抽象类的区别
- 抽象类:可以包含字段和具体方法,单继承。
- 接口:仅定义方法规范(Java 8前),支持多重实现。
abstract class Bird {
abstract void fly();
void breathe() {
System.out.println("Breathing");
}
}
interface Flying {
void takeOff();
void land();
}
实际应用场景
- 解耦:接口定义契约,实现类负责具体逻辑。
- 插件架构:通过接口扩展功能。
- 测试模拟:用接口模拟依赖项(如Mock对象)。
// 服务接口
interface DatabaseService {
void save(String data);
}
// 真实实现
class MySQLService implements DatabaseService {
public void save(String data) {
System.out.println("Saving to MySQL: " + data);
}
}
// 测试模拟
class MockService implements DatabaseService {
public void save(String data) {
System.out.println("[TEST] Saved: " + data);
}
}






