这些形状的通用接口

时间:2015-04-06 04:58:15

标签: java swing oop java-2d

我需要从文件中读取输入并绘制适当的形状。形状可以是矩形,椭圆形,圆形或直线形。我知道如何使用这些。但是,我想知道我是否可以使用通用接口并使用它们中的每一个。

我的意思是,我希望我可以定义为:

Shape currentShape;

然后我可以做:

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

等等。

但是,我无法使用currentShape访问对象的独占方法。

有什么替代方案?
PS:我正在使用swing类。

1 个答案:

答案 0 :(得分: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)
相关问题