在你的例子中,你選擇哪種方式並不重要。你的例子並沒有顯示多態的力量。
讓我們看看多態性的一個簡單的例子:
interface Shape{
void draw();
}
class Rectangle implements Shape{
public void draw(){
System.out.println("Drawing Rectangle.");
}
}
class Triangle implements Shape{
public void draw(){
System.out.println("Drawing Triangle.");
}
}
class Circle implements Shape{
public void draw(){
System.out.println("Drawing Circle.");
}
}
Rectangle
,Triangle
和Circle
只是實現自己draw
函數的定義。
現在,假設您必須在您的Main
類中實施drawAllShapes
方法,該方法需要一堆形狀並將它們全部打印出來。但沒有多態性,這可能是忙碌的,因爲可能有不同類型的形狀。現在,這裏出現了多態性來拯救我們。
class RandomShapeFactory{
public static Shape createRandomShape(){
Shape randomShape;
Random random = new Random();
int randomNo = random.nextInt() % 3 + 1;
if (randomNo == 1){
randomShape = new Rectangle();
}
else if (randomNo == 2){
randomShape = new Triangle();
}
else{
randomShape = new Circle();
}
return randomShape;
}
}
class Main{
public static void main(String[] args){
Shape[] shapes = new Shape[10];
for (int i = 0; i < shapes.length; i++){
shapes[i] = RandomShapeFactory.createRandomShape();
}
drawAllShapes(shapes);
}
public static void drawAllShapes(Shape[] shapes){
for (int i = 0; i < shapes.length; i++){
shapes[i].draw();
}
}
}
的drawAllShapes
此實現不必知道Shape
在指數i
是否是Circle
或Triangle
或者是什麼,它是取其Shape
,它只是要求其執行draw
方法。
main
方法具有所有隨機形狀,並且當傳遞給方法drawAllShapes
時,它們的相關實現將被調用。
這種實現方法也跟在Open/Closed Principle之後,如果你希望將來可以在層次結構中添加更多形狀,drawAllShapes
方法不必知道新形狀,只需添加新類並實現Shape
接口和drawAllShapes
也將使用這些形狀。
請參閱上述示例中的操作here。
查看http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface - 不是你問的問題,但你應該找到答案的啓發。 –
另請參閱此討論:[瞭解「編程到接口」](http://programmers.stackexchange.com/questions/232359/understanding-programming-to-an-interface)。 – DimaSan