Java接口是一種完全抽象的類,它定義了一組方法的簽名(沒有方法體),用于規范類的行為。接口使用interface關鍵字定義,類通過implements關鍵字實現接口。
接口的特點:
- 接口中的方法默認是public abstract的
- 接口中的變量默認是public static final的
- 接口不能包含構造方法
- 從Java 8開始,接口可以包含默認方法和靜態方法
- 從Java 9開始,接口可以包含私有方法
接口在Java中起到了定義標準的作用。當多個類需要遵循相同的行為規范時,可以使用接口來定義這些規范。
示例:`java
// 定義數據庫連接標準
public interface DatabaseConnection {
void connect();
void disconnect();
boolean isConnected();
}
// MySQL實現
public class MySQLConnection implements DatabaseConnection {
public void connect() {
// MySQL連接邏輯
}
public void disconnect() {
// MySQL斷開邏輯
}
public boolean isConnected() {
// 檢查連接狀態
return true;
}
}`
工廠模式使用接口來創建對象,而無需向客戶端暴露創建邏輯。
簡單工廠模式示例:`java
// 產品接口
public interface Shape {
void draw();
}
// 具體產品
public class Circle implements Shape {
public void draw() {
System.out.println("繪制圓形");
}
}
public class Rectangle implements Shape {
public void draw() {
System.out.println("繪制矩形");
}
}
// 工廠類
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) return null;
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}`
代理模式通過接口為其他對象提供代理或占位符,以控制對這個對象的訪問。
靜態代理示例:`java
// 接口
public interface Image {
void display();
}
// 真實對象
public class RealImage implements Image {
private String fileName;
public RealImage(String fileName) {
this.fileName = fileName;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("從磁盤加載圖片: " + fileName);
}
public void display() {
System.out.println("顯示圖片: " + fileName);
}
}
// 代理對象
public class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName) {
this.fileName = fileName;
}
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName);
}
realImage.display();
}
}`
核心區別:
| 特性 | 抽象類 | 接口 |
|------|--------|------|
| 方法實現 | 可以有具體方法 | 只能有抽象方法(Java 8前) |
| 變量 | 可以有各種變量 | 只能是常量 |
| 構造方法 | 可以有 | 不能有 |
| 繼承 | 單繼承 | 多實現 |
| 設計目的 | 代碼復用 | 定義規范 |
選擇原則:
- 當需要定義模板方法或代碼復用時,使用抽象類
- 當需要定義行為規范或實現多態時,使用接口
- 優先使用接口,因為Java支持多接口實現
在GoF設計模式中,接口扮演著至關重要的角色:
接口作為Java面向對象編程的重要特性,不僅提供了代碼規范,更是設計模式實現的基石。掌握接口的使用,能夠寫出更加靈活、可擴展的代碼。
如若轉載,請注明出處:http://www.bmebdlx.cn/product/42.html
更新時間:2026-01-27 00:33:57