R. Morelli
The purpose of the lab exercise is to familiarize you with Java methods and parameters. You will make several modifications to extend the functionality of the CyberPet class. The objectives of the lab are
Modify the provided CyberPet and TestCyberPet classes to create a simulation in which pets can eat different kinds of food. The completed program should be capable of producing the following output:
pet1's name is Socrates
Socrates is eating an apple
Socrates is sleeping
pet2's name is Cleopatra
Cleopatra is eating beans
Cleopatra is sleeping
...
Open the provided CyberPet.java and the TestCyberPet.java source files in your text editor. Compile the classes and run the TestCyberPet class.
For each of the items below, make the editing change and then recompile the program. Make note of any error messages that are generated by the compiler. Try to understand what the message is telling you, and try to learn from the error, so it will be less likely to occur next time. After you have finished with that error, restore the code to its original form and move on to the next item.
Modify the design of the CyberPet class so that it contains a new variable of type String named food.. Then add a new void access method named eat which takes a single String parameter that represents a type of food -- "spinach", "ice cream", and so on. The method should take the food string that is passed to it and assign it to the instance variable food.
Note that this new method will have the same name as an existing method in CyberPet. How will these two methods be distinguished from one another?
Modify the TestCyberPet application program so that it will conduct appropriate tests to make sure your new eat() method is working properly. When you are finished, the output should match the output shown above in the problem statement. Your test algorithm should tell your CyberPet to eat certain foods.
Be sure to make appropriate use of private and public in your revisions to the CyberPet class.
Modify your TestCyberPet program so that it produces the following output:
pet1 name is Socrates
Socrates is sleeping
Socrates is eating an apple
Socrates is eating a Macintosh
Socrates is eating a Windows/PC
Add System.out.println() statements to your eat(String) method in order to generate a visible trace of the method call and return mechanism. Use println to display eat()'s parameter, and the food instance variable both before and after the assignment statement. Try to generate the following output:
starting the eat method
str parameter = bananas
food instance variable = no food
str parameter = bananas
food instance variable = bananas
exiting the eat method
Using println statements to display the values of variables and to trace program control is a good debugging technique. You will want to use this technique to locate bugs when things go wrong.