編程思想-14章-node1-爲什麼需要RTTI

其中提到

面向對象編程的基本目的是:讓代碼只操縱對基類的引用(這個例子中是Shape)。
這樣,如果添加新類(比如從Shape派生出了Rhomboid)擴展程序,不會影響到原來的代碼

abstract class Shape {
  void draw() { System.out.println(this + ".draw()"); }
  abstract public String toString();
}

class Circle extends Shape {
  public String toString() { return "Circle"; }
}

class Square extends Shape {
  public String toString() { return "Square"; }
}

class Triangle extends Shape {
  public String toString() { return "Triangle"; }
}

public class Shapes {
  public static void main(String[] args) {
    List<Shape> shapeList = Arrays.asList(
      new Circle(), new Square(), new Triangle()
    );
    for(Shape shape : shapeList)
      shape.draw();
  }
}

 接下來就是多態的事情了,Shape對象實際執行什麼樣的代碼,是由引用所指向的具體的對象Circle Square 或Triangle來決定的。
通常,也正是這樣要求的:大部分代碼儘可能的少了解對象的 具體類型 ,而是隻與對象家族中的一個通用表示打交道(這個例子中是Shape)。
這樣的代碼更容易寫、容易讀、便於維護;設計也更容易實現、理解和改變。
所以,多態是面向對象編程的基本目標

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章