Lab 15: Static vs. Dynamic Members of a Class in Java

In this lab, you will practice using static and dynamic members of classes to differentiate between properties specific to one object versus properties shared by all objects of a certain type (class). Feel free to work in pairs.

Problem: The Bouncing Ball

For this lab you will implement the class Ball which represents a toy ball. Ball should have a method bounce() whose return type is void, and should have an integer member bounces that counts the number of times the ball has been bounced.

Ball should also have a static method named getTotalBounces which counts the total number of times that any Ball object has been bounced. To do this, you will want to include a static integer member totalBounces which counts the total number of bounces. Once implemented the following code in the main of UseBall should output the number 2 (You should create UseBall.java as well, right?):

    Ball b1 = new Ball();
    Ball b2 = new Ball();
    b1.bounce();
    b2.bounce();
    System.out.println(Ball.getTotalBounces());

Next, we will add some functionality to Ball.

  1. First, implement a method void reset(int count) which sets bounces to the value provided in count. How does this affect totalBounces?

  2. Next, include an integer variable to keep track of the total number of balls which have been created. Should this variable be static or dynamic? Use this variable to implement the static method getAverageBounces() which returns the average of the number of times that any ball has been bounced.

  3. Finally, as a challenge, try to implement the static method bounceAll() which bounces each of the balls at once. This will be difficult unless you include one more static integer member in the class - and even then it might be a bit tricky. Give it your best shot, and don't hesitate to ask the lab assistants for help!

When you are done:

When you are done with these, feel free to leave the lab.