首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 多態實戰:Shape 體系與動態綁定的魔力

     編輯:Java 相關知識

經典 Shape 例子

基類 Shape 定義通用協議:draw()、erase()。衍生類 Circle、Square、Triangle 覆寫實現具體行為。

向上轉型與動態綁定

Shape s = new Circle(); // 向上轉型:Circle 是 Shape
s.draw(); // 調用 Circle.draw(),而非 Shape.draw()!

編譯器見 Shape 引用,但運行期 JVM 根據對象實際類型(Circle)決議調用 Circle.draw()。這就是後期綁定/動態綁定。

Shapes 完整示例

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,主循環零修改。這就是多態賦予的擴展力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved