若類別 A 僅表示一個抽象概念(如「幾何圖形」),不應被實例化。宣告為 abstract 可強制子類實作抽象方法,並確保多態行為。
abstract class Shape {
abstract double area();
abstract double perimeter();
// 共同行為:比較面積
int compareArea(Shape other) {
return Double.compare(this.area(), other.area());
}
}
class Circle extends Shape {
double radius;
double area() { return Math.PI * radius * radius; }
double perimeter() { return 2 * Math.PI * radius; }
}
class Rectangle extends Shape {
double width, height;
double area() { return width * height; }
double perimeter() { return 2 * (width + height); }
}
area()、perimeter()。compareArea 定義於父類,所有子類自動擁有比較能力,無需重寫。new Shape() 編譯報錯,語義更清晰。抽象類是「定義介面、共享實作、強制契約」的最佳工具,配合多態實現開放封閉原則。