In the programs that you have written so far, you have used the
Canvas class to draw pictures. While you undoubtedly had a lot of fun
coming up with different drawings, the problem is that you have to
"hard code" whatever you want to draw. In other words, every time you
want to change your drawing, you have to change the code and recompile
it. Perhaps you find yourself drawing the same things over and over
again, and you'd like to specify a way to just draw, say, a car,
simply by calling a method that you've written to do so. This can be
done by defining a Car
class, and then creating multiple
objects from that class.
In this lab, you will take a very small class called
Car
and gradually add new capabilities to it. By the end
of the lab, you'll have a picture of a bunch of cars on a road, plus a
bit more knowledge about the structure of Java classes.
Car
and Road
classesCreate a directory named lab4
, and copy Car.java, Road.java, and
Canvas.java into it.
Take a look first at Road.java
. What do you expect to
see when you run java Road
? Notice that it uses objects
from the class Car
that we are creating. Take a look at
Car.java
to see how to set up a class that we can create
objects from.
Compile all of the java
files. Does the
picture look like you expected it to? If not, take a closer look at
the code.
Car
of a different color You may have noticed a tragic uniformity in the color of the cars. Let's fix that.
Color
object variable (call it
bodyColor
) to the Car
class. The variable
should be declared near the top of the class, right along with the
declarations for the other object variables.setColor
method to the Car
class. This method should begin with "public void
setColor(Color newColor)
", and it should simply assign a
new value to the bodyColor
instance variable.Car
constructor to set the
bodyColor
variable to the default value (red).draw
method to use bodyColor
instead of red.main
in Road
to change
the color of one of the cars to ecru or beige or tan or eggshell
or something.Now that you can control the color of your Car
, let's
try changing the size of the car. You can start by following
instructions like those in the previous section: add a
width
instance variable to Car
, add a
setWidth
method, initialize width
in the
constructor, and change main
in Road
.
The tricky part will be changing draw
. In the
original version of draw
, you'll see numbers that depend
on the width of the car being 100. But now you'll need to change
those numbers to expressions that vary depending on the value of
width
.
You'll know you have gotten it right if you can modify the widths of your cars and get different-colored cars of different sizes on your road.
Hand in your entire lab4 directory, including Car.java, Road.java, Tree.java, and Landscape.java by Sunday, 16 April 2006, at 11:59pm.
Have fun.