Objects and instance variables

Open up PiggyBank.java and read the javadoc comment at the top to see how it is supposed to work. If you run the main method of PiggyBankExample, you can see that the results are not quite right.

  1. Set a breakpoint at the first line of main and run in Debug mode.
  2. Use Step Over or F6 to execute the first line, and take a look at the Variables pane again. You see the parameter args and also the local variable piggy.
  3. Since piggy is an object, all we initially see for its value is the name of the class. But when you hover the cursor over that line of the table, a small triangle appears on the left. Click the triangle to expand. Now you can see the values of the three instance variables in the object.
  4. The green highlight should now be over the call to addCoins.
  5. Use Step Into or F5 to enter the addCoins method. Notice that the Variables pane doesn't show any local variables, since they haven't been defined yet, but it includes something called this. The implicit variable this always refers to the object on which the executing method was invoked (here it is the PiggyBank we created in main).
  6. Hover over the this line of the Variables pane; again the little triangle appears so you can expand and see the instance variables.

  7. Now use Step Over or F6 twice. You can see the two local variables in the Variables pane.
  8. Use Step Over or F6 twice more, to execute the line coins = newCoins. You can see the instance variable coins updated in the Variables pane.
  9. Step again to return to main.
  10. Step over (F6) the next line in main (another call to addCoins()).
  11. The next line of main is a println statement. The line actually contains two method calls, one to println(), and one to getNumCoins() . If we press Step Into again, which one do we go into? In this case, the runtime has to evaluate the argument to println before it can execute println, so the debugger will step into the getNumCoins() method first. Try it, and continue stepping over until you get back to main. Keep an eye on the instance variables and identify the error!
    • Remember, if you accidentally step into any Java library code, such as the println method, you can use Step Return or F7 to get back.
  12. When you get to the next line in main, step into the isSmashed()method. Keep an eye on the instance variables, and you should be able to spot the other error.
  13. Terminate the program, fix the error, and check that the results are correct now.

Checkpoint 2

Demonstrate to the TA that you can set breakpoints, single step through code, step return from a method such as println and view instance variables of objects. Explain the error you found in PiggyBank.