Reputation: 567
I need to read input from a file and draw the appropriate shape. The shape can be a rectangle, ellipse, circle or a line. I know how to work with all these. However, I was wondering if I could use a common interface and work with each of them.
I mean, I wish I could have something defined as:
Shape currentShape;
and then I can do:
currentShape = new Rectangle(-);
currentShape = new Ellipse2D.Double(-);
and so on.
However, I cannot access the exclusive methods of the objects using the currentShape.
What is the alternative?
PS: I'm using the swing class.
Upvotes: 0
Views: 57
Reputation: 7769
Well, you cannot access the methods for the dynamic type (Rectangle, Double etc..) because the static type is a parent (Shape). But here's how you can cast it:
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)
Upvotes: 1