interface 關鍵字定義一組方法簽名與常量,零實現。類通過 implements 承諾履行契約,單類可實現多接口,實現「多重類型」而非「多重實現繼承」。
public interface Flyable { void fly(); }
public interface Talkable { void talk(); }
public interface Message { int MAX_SIZE = 4096; String getMessage(); }
public class Parrot implements Flyable, Talkable {
public void fly() { System.out.println("Flying like a parrot…"); }
public void talk() { System.out.println("Hello! I am a parrot!"); }
}
public class TextMessage implements Message {
private String content;
public void setMessage(String msg) {
this.content = msg.length() > MAX_SIZE ? msg.substring(0, MAX_SIZE) : msg;
}
public String getMessage() { return content; }
}
public interface AppConstants {
String ROOT_PATH = "/app";
int MAX_RETRY = 3;
// 甚至動態初始化常量
String VERSION = getClass().getPackage().getImplementationVersion();
}
使用:AppConstants.ROOT_PATH,無需實例化。
public interface User {
int getAge(); String getName(); String getPassword();
}
public interface UserFactory {
User getUser(String name);
User createUser(String name, String pwd, int age);
}
// XML 實現
class XMLUser implements User { /* ... */ }
class XMLUserFactory implements UserFactory { /* ... */ }
// 客戶端零耦合
UserFactory factory = FactoryProvider.getFactory(); // 可換 JDBC/JPA 實現
User admin = factory.getAdmin();
RMI 遠程接口繼承 java.rmi.Remote,方法拋出 RemoteException:
public interface Product extends Remote {
String getName() throws RemoteException;
}
public class ProductImpl extends UnicastRemoteObject implements Product {
private final String name;
public ProductImpl(String n) throws RemoteException { name = n; }
public String getName() throws RemoteException { return name; }
}
AWT/Swing、Spring 事件、Guava EventBus 均以接口定義回調:
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
button.addActionListener(e -> System.out.println("Clicked!"));
default 方法:提供默認實現,不破壞現有實現類static 方法:工具方法歸屬接口,如 Stream.of()private 方法:default 方法間復用邏輯@FunctionalInterface 註解驗證default,破壞性變更新建接口(如 List → Collection)