26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 Object-Oriented <strong>Program</strong>ming 535<br />

in the application’s construc<strong>to</strong>r). The paint method (for your subclass of JFrame) should draw<br />

the shape with a statement like<br />

currentShape.draw( g );<br />

where currentShape is the MyShape reference and g is the Graphics object that the shape<br />

will use <strong>to</strong> draw itself on the background of the window.<br />

9.29 Next, change the single MyShape reference in<strong>to</strong> an array of MyShape references and hard<br />

code several MyLine objects in<strong>to</strong> the program for drawing. The application’s paint method should<br />

walk through the array of shapes and draw every shape.<br />

After the preceding part is working, you should define the MyOval and MyRect classes and<br />

add objects of these classes in<strong>to</strong> the existing array. For now, all the shape objects should be created in<br />

the construc<strong>to</strong>r for your subclass of JFrame. In Chapter 12, we will create the objects when the user<br />

chooses a shape and begins drawing it with the mouse.<br />

In Exercise 9.28, you defined a MyShape hierarchy in which classes MyLine, MyOval and<br />

MyRect subclass MyShape directly. If the hierarchy was properly designed, you should be able <strong>to</strong><br />

see the tremendous similarities between the MyOval and MyRect classes. Redesign and reimplement<br />

the code for the MyOval and MyRect classes <strong>to</strong> “fac<strong>to</strong>r out” the common features in<strong>to</strong> the<br />

abstract class MyBoundedShape <strong>to</strong> produce the hierarchy in Fig. 9.46.<br />

Class MyBoundedShape should define two construc<strong>to</strong>rs that mimic the construc<strong>to</strong>rs of class<br />

MyShape and methods that calculate the upper-left x-coordinate, upper-left y-coordinate, width and<br />

height. No new data pertaining <strong>to</strong> the dimensions of the shapes should be defined in this class.<br />

Remember, the values needed <strong>to</strong> draw an oval or rectangle can be calculated from two (x,y) coordinates.<br />

If designed properly, the new MyOval and MyRect classes should each have two construc<strong>to</strong>rs<br />

and a draw method.<br />

Fig. Fig. 9.46 9.46 The MyShape hierarchy.<br />

java.lang.Object<br />

MyShape<br />

MyLine MyBoundedShape<br />

MyOval<br />

MyRect<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!