2015-04-06 19 views
0

我需要從文件讀取輸入並繪製適當的形狀。形狀可以是矩形,橢圓形,圓形或直線。我知道如何與所有這些工作。但是,我想知道我是否可以使用通用接口並與它們一起工作。這些形狀的通用接口

我的意思是,我希望我能有一些定義爲:

Shape currentShape; 

,然後我可以這樣做:

currentShape = new Rectangle(-); 
currentShape = new Ellipse2D.Double(-); 

等。

但是,我無法使用currentShape訪問對象的排他方法。

什麼是替代方案?
PS:我正在使用鞦韆班。

+0

*「不過,我無法訪問使用currentShape對象的唯一方法。」 *你爲什麼需要 – MadProgrammer 2015-04-06 05:04:20

+0

@MadProgrammer:其實,在這種情況下,你」再右吧。但是,當案件出現時,知道如何處理這個問題會很方便。 – 2015-04-06 05:30:52

+0

但是,爲什麼呢?你可以使用重塑來改變形狀的邊界,它可以被繪製。你想要達到什麼功能? – MadProgrammer 2015-04-06 05:47:05

回答

1

那麼,你不能訪問動態類型(Rectangle,Double等..)的方法,因爲靜態類型是父類(Shape)。但這裏是你如何能投它:

Shape currentShape; 
currentShape = new Ellipse2D.Double(); 

if(currentShape instanceof Ellipse2D.Double){ 
    Ellipse2D.Double tmpShape = (Ellipse2D.Double) currentShape; 

    // Code goes here 
} // else if (same for Rectangle, or any other child of Shape) 
+0

謝謝你澄清事情。欣賞。 – 2015-04-06 05:31:11

+0

@Grendan歡迎您,如果您沒有其他問題,請將其標記爲已解決:) – CMPS 2015-04-06 05:32:22

+1

OPs永不接受..... – mKorbel 2015-04-06 11:05:14