傳統 OOP 強調「對象屬於某類型」,操作針對類型。但現實中我們更關心對象具備什麼能力:
結論:類型不重要,能力才重要。Java 用接口表示能力。
// 定義能力
public interface MyComparable {
int compareTo(Object other); // -1/0/1
}
// 實現能力
public class Point implements MyComparable {
private int x, y;
public Point(int x, int y) { this.x=x; this.y=y; }
public double distance() { return Math.sqrt(x*x+y*y); }
@Override
public int compareTo(Object other) {
if(!(other instanceof Point)) throw new IllegalArgumentException();
Point p = (Point)other;
double d = distance() - p.distance();
return d<0?-1 : d>0?1 : 0;
}
}
MyComparable p1 = new Point(2,3);
MyComparable p2 = new Point(1,2);
System.out.println(p1.compareTo(p2)); // 1
// 通用工具類,不知具體類型,只依賴接口
public class CompUtil {
public static Object max(MyComparable[] objs) { ... }
public static void sort(MyComparable[] objs) { ... }
}
// 調用
Point[] points = {new Point(2,3), new Point(3,4), new Point(1,2)};
CompUtil.sort(points); // [(1,2), (2,3), (3,4)]
public static final,本質是常量interface C extends A, B,支援多繼承class C extends Base implements I1, I2,extends 在前繼承提供代碼復用+多態,但破壞封裝、耦合強。
組合復用代碼但無多態。
接口提供多態,組合復用代碼,兩者結合兼得兩全:
interface IAdd { void add(int n); void addAll(int[] ns); }
class Base implements IAdd { ... } // 復用邏輯
class Child implements IAdd { // 組合 Base 或獨立實現
private Base base = new Base();
public void add(int n) { base.add(n); }
public void addAll(int[] ns) { base.addAll(ns); }
}
「面向接口編程」是分解複雜問題、降低耦合、提升靈活性的核心工具。它將「是什麼」(類型)轉為「能做什麼」(能力),更貼近領域本質。下一步將探討介於接口與類之間的抽象類。