Java Reference
In-Depth Information
classes have many similarities. Using inheritance, we can “factor out” the common features
from all three classes and place them in a single shape
superclass
. Then, using variables of
the superclass type, we can manipulate shape objects
polymorphically
. Removing the re-
dundant code will result in a smaller, more flexible program that's easier to maintain.
GUI and Graphics Case Study Exercises
10.1
Modify the
MyLine
,
MyOval
and
MyRectangle
classes of GUI and Graphics Case Study
Exercise 8.1 and Exercise 9.1 to create the class hierarchy in Fig. 10.17. Classes of the
MyShape
hi-
erarchy 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 hier-
archy, it can manipulate it
polymorphically
for the rest of its lifetime as a
MyShape
.
java.lang.Object
MyShape
MyLine
MyOval
MyRectangle
Fig. 10.17
|
MyShape
hierarchy.
In your solution, class
MyShape
in Fig. 10.17
must
be
abstract
. Since
MyShape
represents any
shape in general, you cannot implement a
draw
method without knowing
specifically
what shape it
is. The data representing the coordinates and color of the shapes in the hierarchy should be
declared as
private
members of class
MyShape
. In addition to the common data, class
MyShape
should declare the following methods:
a)
A
no-argument constructor
that sets all the coordinates of the shape to
0
and the color to
Color.BLACK
.
b)
A constructor that initializes the coordinates and color to the values of the arguments
supplied.
c)
Set
methods for the individual coordinates and color that allow the programmer to set
any piece of data independently for a shape in the hierarchy.
d)
Get
methods for the individual coordinates and color that allow the programmer to re-
trieve any piece of data independently for a shape in the hierarchy.
e)
The
abstract
method
public
abstract
void
draw(Graphics g);
which the program's
paintComponent
method will call to draw a shape on the screen.
To ensure proper encapsulation, all data in class
MyShape
must be
private
. This requires
declaring proper
set
and
get
methods to manipulate the data. Class
MyLine
should provide a no-
argument constructor and a constructor with arguments for the coordinates and color. Classes
MyOval
and
MyRectangle
should provide a no-argument constructor and a constructor with argu-