← 返回首页

Java接口:定义契约与规范

📂 java ⏱ 2 min 325 words

Java接口:定义契约与规范

概述

接口(Interface)是Java中定义行为规范的机制。类通过实现接口来承诺提供特定的功能,从而实现松耦合的设计。Java 8后接口还支持默认方法和静态方法。

1. 接口的定义与实现

// 定义接口
public interface Printable {
    void print();
    String getFormat();
}

// 实现接口
public class Document implements Printable {
    private String content;

    public Document(String content) {
        this.content = content;
    }

    @Override
    public void print() {
        System.out.println("打印文档: " + content);
    }

    @Override
    public String getFormat() {
        return "PDF";
    }
}

2. 接口中的常量与方法

public interface DatabaseConfig {
    // 常量(默认public static final)
    int MAX_CONNECTIONS = 100;
    String DEFAULT_ENCODING = "UTF-8";

    // 抽象方法
    void connect();
    void disconnect();

    // 默认方法(Java 8+)
    default void log(String message) {
        System.out.println("[DB] " + message);
    }

    // 静态方法(Java 8+)
    static boolean validateUrl(String url) {
        return url != null && url.startsWith("jdbc:");
    }
}

3. 接口继承

public interface Readable {
    String read();
}

public interface Writable {
    void write(String content);
}

// 接口可以继承多个接口
public interface FileManager extends Readable, Writable {
    void delete();
    default void save() {
        write(read());
    }
}

4. 多重实现

public interface Serializable {
    byte[] serialize();
}

public interface Comparable<T> {
    int compareTo(T other);
}

public class DataObject implements Serializable, Comparable<DataObject> {
    private String id;
    private String data;

    public DataObject(String id, String data) {
        this.id = id;
        this.data = data;
    }

    @Override
    public byte[] serialize() {
        return data.getBytes();
    }

    @Override
    public int compareTo(DataObject other) {
        return this.id.compareTo(other.id);
    }
}

5. 函数式接口

@FunctionalInterface
public interface Calculator {
    double calculate(double a, double b);

    // 默认方法
    default double add(double a, double b) {
        return calculate(a, b);
    }
}

// 使用Lambda表达式
public class CalculatorTest {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        Calculator multiply = (a, b) -> a * b;

        System.out.println(add.calculate(3, 4));       // 7.0
        System.out.println(multiply.calculate(3, 4));   // 12.0
    }
}

6. 接口与抽象类的对比

// 抽象类:可以有状态和构造方法
public abstract class Animal {
    protected String name;
    public Animal(String name) { this.name = name; }
    public abstract void makeSound();
}

// 接口:只定义行为契约
public interface Swimmable {
    void swim();
    default String getSwimStyle() { return "自由泳"; }
}

最佳实践

  1. 接口隔离原则:接口应该小而专一
  2. 优先使用接口:类可以实现多个接口
  3. 合理使用默认方法:为接口提供向后兼容的扩展
  4. 使用@FunctionalInterface:标记函数式接口

总结

接口是Java实现松耦合和多态的重要机制。掌握接口的定义、实现和使用,可以帮助你设计出更加灵活、可维护的系统。