CS 161 Lab #4

September 24th

Goals:

This week it's all about conditionals and object references! We'll work with the CircleDrawer class from lecture, extending it to add some new functionality. Along the way you'll write code that uses and manipulates object references, and requires more complex Boolean expressions than you've written previously.

Directions:

  1. Download the CircleDrawerLab project and extract its contents, then start BlueJ and open the project.
  2. Take a moment to familiarize yourself with the Java code in the CircleDrawer class. A CircleDrawer instance contains references to a pair of circles (first, second), and can make the circles visible or invisible. You can prove this by doing the following:
    1. Create two circles on the object workbench. Make them each visible, and move them in different directions (e.g. moveUp, moveDown etc.) so you can tell them apart. Different colors would help, too.
    2. Create a new CircleDrawer instance. BlueJ will ask you for two circle references to pass to the constructor. Type the names of your circles into the boxes so the new CircleDrawer will "control" the two circles you've created.
    3. Invoke eraseCircles on your CircleDrawer object and notice that they both disappear. Run drawCircles and both will reappear.
    4. Note that you can make a circle visible (or invisible) either by asking the CircleDrawer to do it, or by invoking the appropriate method directly on a circle — both refer to the same circle!
  3. Back in CircleDrawer, modify the drawCircles method so that it only draws circles with radii greater than 20 and less than 50. (You can use the getDiameter method in the Circle class to find out how large a circle is — do not change the Circle class!) In other words, instead of always calling makeVisible on both circles, check to see if the radius is in the right range before drawing. Remember that you can use the Boolean and operator (&&) to build more complex tests. Also, when testing your modified method, don't forget that you can still invoke changeSize on the circles you've created on the object workbench.
  4. Modify the addCircle method so that it returns a reference to the circle that's being eliminated. This is a little tricky since the return statement needs to be at the end of the method, but if you're not careful, you'll have lost track of the circle by then. Verify that your modified works! For example, you could make the returned circle visible again, or just use the object inspector to verify that it has the same attributes as the old "first" circle did. (When you call the method from BlueJ, you can click the "Get" button in the method result box to put the returned object on the desktop.)
If time permits, consider trying one of the following exercises:


Brad Richards, 2009