19.6. Managing Shapes
When you create shapes in Sketcher, you'll have no idea of the sequence of shape types that will occur. This is determined totally by the person using the program to produce a sketch. You'll therefore need to be able to draw shapes and perform other operations on them without knowing what they are—and of course polymorphism can help here.
You don't want to use the shape classes defined in java.awt.geom directly as you'll want to add your own attributes such as color or line style for the shapes that can be drawn in Sketcher and store them as part of the object. You could consider using the shape classes as base classes for your shapes, but you couldn't use the GeneralPath class in this scheme of things because, as I said earlier, the class has been defined as final and therefore cannot be subclassed. You could consider defining an interface that all your shape classes would implement. However, some methods have a common implementation in all your shape classes, which would mean that you would need to repeat this code in every class.
Taking all of this into account, the easiest approach might be to define a common base class for the Sketcher shape classes and include a member in each class to store a shape object of one kind or another. You'll then be able to include a polymorphic method to return a reference to a shape as type Shape for use with the draw() method of a Graphics2D object.
You can start by defining a base class, Element, from which you'll derive ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.