該現象通過繼承被稱爲多態性。這意味着你的行爲在運行時決定在哪個對象被調用,而不是由它被調用的引用決定。
好吧。讓我們進一步擴展您的範例讓我們先創建的類層次
class Shape{
public void draw(){}
}
class Circle extends Shape{
public void draw(){
//mechanism to draw circle
}
}
class Square extends Shape{
public void draw(){
//mechanism to draw square
}
}
現在讓我們看看這是如何導致乾淨的代碼
class Canvas{
public static void main(String[] args){
List<Shape> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Square());
// clean and neat code
for(Shape shape : shapes){
shape.draw();
}
}
}
這也可以使得鬆耦合系統
Class ShapeDrawer{
private Shape shape;
public void setShape(Shape shape){
this.shape = shape;
}
public void paint(){
shape.draw();
}
}
在這種情況下幫助,ShapeDrawer
與實際形狀非常鬆散地結合在一起。 ShapeDrawer
甚至不知道它正在繪製哪種類型的Shape
,甚至不知道它如何繪製的機制是從中抽取。繪製特定形狀的底層機制可以在不影響該類的情況下進行更改。
來源
2014-09-03 18:26:04
Adi
這裏討論這樣的通用問題是不合時宜的。 – talex 2014-09-03 18:23:14
也許下面會有幫助嗎? http://stackoverflow.com/questions/11064409/why-to-use-polymorphism – 2014-09-03 18:24:34
因爲真正的程序比這個玩具的例子複雜得多。 – chrylis 2014-09-03 18:35:10