Java接口是一種完全抽象的類,它定義了一組方法的簽名(沒(méi)有方法體),用于規(guī)范類的行為。接口使用interface關(guān)鍵字定義,類通過(guò)implements關(guān)鍵字實(shí)現(xiàn)接口。
接口的特點(diǎn):
- 接口中的方法默認(rèn)是public abstract的
- 接口中的變量默認(rèn)是public static final的
- 接口不能包含構(gòu)造方法
- 從Java 8開(kāi)始,接口可以包含默認(rèn)方法和靜態(tài)方法
- 從Java 9開(kāi)始,接口可以包含私有方法
接口在Java中起到了定義標(biāo)準(zhǔn)的作用。當(dāng)多個(gè)類需要遵循相同的行為規(guī)范時(shí),可以使用接口來(lái)定義這些規(guī)范。
示例:`java
// 定義數(shù)據(jù)庫(kù)連接標(biāo)準(zhǔn)
public interface DatabaseConnection {
void connect();
void disconnect();
boolean isConnected();
}
// MySQL實(shí)現(xiàn)
public class MySQLConnection implements DatabaseConnection {
public void connect() {
// MySQL連接邏輯
}
public void disconnect() {
// MySQL斷開(kāi)邏輯
}
public boolean isConnected() {
// 檢查連接狀態(tài)
return true;
}
}`
工廠模式使用接口來(lái)創(chuàng)建對(duì)象,而無(wú)需向客戶端暴露創(chuàng)建邏輯。
簡(jiǎn)單工廠模式示例:`java
// 產(chǎn)品接口
public interface Shape {
void draw();
}
// 具體產(chǎn)品
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;
}
}`
代理模式通過(guò)接口為其他對(duì)象提供代理或占位符,以控制對(duì)這個(gè)對(duì)象的訪問(wèn)。
靜態(tài)代理示例:`java
// 接口
public interface Image {
void display();
}
// 真實(shí)對(duì)象
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);
}
}
// 代理對(duì)象
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();
}
}`
核心區(qū)別:
| 特性 | 抽象類 | 接口 |
|------|--------|------|
| 方法實(shí)現(xiàn) | 可以有具體方法 | 只能有抽象方法(Java 8前) |
| 變量 | 可以有各種變量 | 只能是常量 |
| 構(gòu)造方法 | 可以有 | 不能有 |
| 繼承 | 單繼承 | 多實(shí)現(xiàn) |
| 設(shè)計(jì)目的 | 代碼復(fù)用 | 定義規(guī)范 |
選擇原則:
- 當(dāng)需要定義模板方法或代碼復(fù)用時(shí),使用抽象類
- 當(dāng)需要定義行為規(guī)范或?qū)崿F(xiàn)多態(tài)時(shí),使用接口
- 優(yōu)先使用接口,因?yàn)镴ava支持多接口實(shí)現(xiàn)
在GoF設(shè)計(jì)模式中,接口扮演著至關(guān)重要的角色:
接口作為Java面向?qū)ο缶幊痰闹匾匦裕粌H提供了代碼規(guī)范,更是設(shè)計(jì)模式實(shí)現(xiàn)的基石。掌握接口的使用,能夠?qū)懗龈屿`活、可擴(kuò)展的代碼。
如若轉(zhuǎn)載,請(qǐng)注明出處:http://www.xibeiyouxi.cn/product/42.html
更新時(shí)間:2026-01-15 11:54:24