Java 接口详解
1. 接口的基本概念
接口(Interface)是Java中一种完全抽象的类,用于定义一组规范或契约。接口只包含抽象方法(Java 8之前)和常量,实现类必须实现接口中定义的所有方法。
2. 接口的定义语法
[访问修饰符] interface 接口名 [extends 父接口1, 父接口2...] {
// 常量定义(默认 public static final)
// 抽象方法定义(默认 public abstract)
// 默认方法(Java 8+)
// 静态方法(Java 8+)
// 私有方法(Java 9+)
}
3. 接口的特点
3.1 成员变量
public interface Vehicle {
// 默认是 public static final
int MAX_SPEED = 200;
String BRAND = "Generic Vehicle";
// 等同于:
// public static final int MAX_SPEED = 200;
}
3.2 抽象方法
public interface Vehicle {
// 默认是 public abstract
void start();
void stop();
void accelerate(int speed);
// 等同于:
// public abstract void start();
}
4. 接口的实现
4.1 基本实现
// 定义接口
public interface Animal {
void eat();
void sleep();
void makeSound();
}
// 实现接口
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");
}
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
}
4.2 多接口实现
// 接口1
public interface Swimmable {
void swim();
}
// 接口2
public interface Flyable {
void fly();
}
// 实现多个接口
public class Duck implements Swimmable, Flyable {
@Override
public void swim() {
System.out.println("Duck is swimming");
}
@Override
public void fly() {
System.out.println("Duck is flying");
}
}
5. Java 8 新特性
5.1 默认方法(Default Methods)
public interface Calculator {
// 抽象方法
int add(int a, int b);
// 默认方法
default int subtract(int a, int b) {
return a - b;
}
default String getDescription() {
return "This is a calculator";
}
}
// 实现类
public class BasicCalculator implements Calculator {
@Override
public int add(int a, int b) {
return a + b;
}
// 不需要实现默认方法
}
5.2 静态方法(Static Methods)
public interface MathOperations {
// 静态方法
static double pi() {
return 3.14159;
}
static int max(int a, int b) {
return a > b ? a : b;
}
}
// 使用
public class Test {
public static void main(String[] args) {
double piValue = MathOperations.pi();
int maxValue = MathOperations.max(10, 20);
}
}
6. Java 9 新特性
6.1 私有方法
public interface DatabaseOperations {
default void connect() {
establishConnection();
authenticate();
System.out.println("Connected to database");
}
default void disconnect() {
closeResources();
System.out.println("Disconnected from database");
}
// 私有方法
private void establishConnection() {
System.out.println("Establishing connection...");
}
private void authenticate() {
System.out.println("Authenticating...");
}
private void closeResources() {
System.out.println("Closing resources...");
}
}
7. 接口继承
7.1 接口的多重继承
// 基础接口
public interface Animal {
void eat();
}
// 扩展接口
public interface Mammal extends Animal {
void giveBirth();
}
// 进一步扩展
public interface Pet extends Mammal {
void play();
}
// 实现类
public class Dog implements Pet {
@Override
public void eat() {
System.out.println("Dog is eating");
}
@Override
public void giveBirth() {
System.out.println("Dog gives birth to puppies");
}
@Override
public void play() {
System.out.println("Dog is playing");
}
}
8. 实际应用示例
8.1 策略模式示例
// 策略接口
public interface PaymentStrategy {
void pay(double amount);
}
// 具体策略
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using Credit Card: " + cardNumber);
}
}
public class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using PayPal: " + email);
}
}
// 上下文类
public class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(double amount) {
paymentStrategy.pay(amount);
}
}
8.2 工厂模式示例
// 产品接口
public interface Shape {
void draw();
double area();
}
// 具体产品
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing Circle");
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
@Override
public double area() {
return width * height;
}
}
// 工厂接口
public interface ShapeFactory {
Shape createShape();
}
// 具体工厂
public class CircleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Circle(5.0);
}
}
public class RectangleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Rectangle(4.0, 6.0);
}
}
9. 接口 vs 抽象类
特性 | 接口 | 抽象类 |
---|---|---|
方法 | 所有方法默认public abstract | 可以有具体方法和抽象方法 |
变量 | 只能是public static final常量 | 可以有各种变量 |
构造器 | 不能有构造器 | 可以有构造器 |
多重继承 | 一个类可以实现多个接口 | 一个类只能继承一个抽象类 |
设计目的 | 定义行为规范 | 提供通用实现 |
10. 最佳实践
- 接口命名:使用形容词或名词,通常以"-able"结尾
- 单一职责:每个接口应该只关注一个特定的功能
- 接口隔离:不要创建过于庞大的接口
- 默认方法谨慎使用:避免在默认方法中修改实现类的状态
11. 总结
接口是Java中实现多态和抽象的重要机制,随着Java版本的更新,接口的功能不断增强。合理使用接口可以提高代码的灵活性、可扩展性和可维护性,是实现面向对象设计中"针对接口编程,而不是针对实现编程"原则的关键工具。