基類 Shape 定義通用協議:draw()、erase()。衍生類 Circle、Square、Triangle 覆寫實現具體行為。
Shape s = new Circle(); // 向上轉型:Circle 是 Shape s.draw(); // 調用 Circle.draw(),而非 Shape.draw()!
編譯器見 Shape 引用,但運行期 JVM 根據對象實際類型(Circle)決議調用 Circle.draw()。這就是後期綁定/動態綁定。
class Shape { void draw() {} void erase() {} }
class Circle extends Shape { void draw() { println("Circle.draw()"); } void erase() { println("Circle.erase()"); } }
class Square extends Shape { void draw() { println("Square.draw()"); } ... }
class Triangle extends Shape { void draw() { println("Triangle.draw()"); } ... }
static Shape randShape() {
switch((int)(Math.random()*3)) {
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
Shape[] s = new Shape[9];
for (int i=0; i
輸出示例
Circle.draw()
Triangle.draw()
Circle.draw()
Circle.draw()
Circle.draw()
Square.draw()
Triangle.draw()
Square.draw()
Square.draw()
每次運行結果不同(隨機創建),但每次調用都精準命中實際類型的方法。編譯期完全不知情,純靠運行期動態綁定。
為什麼這很重要?
新增 Pentagon 只需繼承 Shape 實現 draw(),randShape() 加個 case,主循環零修改。這就是多態賦予的擴展力。