I'm doing the exercise 10.1, page 476 from the book Java: How To Program, Early Objects by Paul and Harvey Deitel (10th Edition).
Modify the MyLine, MyOval and MyRectangle classes of GUI to create the class hierarchy as shown in picture below. Classes of the MyShape hierarchy should be “smart” shape classes that know how to draw themselves (if provided with a Graphics object that tells them where to draw). Once the program creates an object from this hierarchy, it can manipulate it polymorphically for the rest of its lifetime as a MyShape.
MyRectangle which we're supposed to modify, all inherit from
JPanel and therefore easily paint themselves with the help of
However in the exercise
MyRectangle must inherit from a class other than
I'm thinking how to approach this. One solution would be creating another class, say
MyPanel which would inherit from
JPanel. Then the constructor in
MyPanel would receive a
MyShape object (
MyRectangle) and the draw it using
paintComponent(). In that case
MyPanel would also have to know what kind of object is
MyShape so I'd have to perform multiple checks with either
instanceof or pass a parameter to
MyPanel indicating exactly what shape I'm interested in so
paintComponent() knows what to draw.
I'm really not sure what is the best practice in such case.