Using Objects
Using Objects based on Existing Classes
- object orientation
- new
- dot operator
- using instance variables
- calling methods
BunnyHarness.java depends on a class Bunny.
Deitel Chapter 3
Classwork
Part A
Create a project and in it a class
with a main, TwoAnimals.
☑ Copy my
Bunny class and
Cat class into your project.
Except for fixing the package statements you do not need to edit
anything in these files to do this classwork. In fact, reading them will probably
just be confusing -- they have material we will cover later. They
are just there so you can use use Bunny and Cat objects your program
For information about the variables and methods in these
classes look at Bunny Documentation and Cat
Documentation
☑ In your main method:
- create a Bunny variable (remember to use "new").
- give the Bunny a name of your choosing
- print the Bunny
(using println, like we print anything else), and then print just
the Bunny's name
- make the Bunny hop
- feed the Bunny 3 carrots by calling the Bunny's feed method 3
times.
- OR feed the Bunny 17 carrots by passing 17 to the Bunny's feed method (put
it in the parens of the feed method, like
passing a string you want to print to the println method)
- print the Bunny again, and then just the Bunny's carrotcount
- make the Bunny hop again
You can base this code on the example in BunnyHarness but for the Bunny variable name and Bunny's name, use values different from in the example. Remove any code copied from the example that you don't use.
Make sure your program runs okay.
Part B
☑ Continuing in main after the code you wrote earlier,
- create a Cat variable
- give the Cat a name of your choosing
- print the Cat
- make the Cat miaow
- feed the Bunny to the Cat by passing your Bunny variable to the Cat's eat method
(put it in the parens of the eat method, like
passing a string you want to print to the println method)
- print out the Bunny's name again (it will have been changed after being
eaten)
This code will be very much like what you did above with the Bunny.