Object Arrays


Object Arrays

ArrayExamples.java
(uses Bunny.java)
 

Classwork


Part A

Create a project.  Add a class with a main and also the class Bunny given above.

In the class with main, write a method showBunnys which takes as parameter an array of Bunnys and prints them out, one per line.

Then add a method makeBunnys which takes as parameter an array of Strings, and returns an array of Bunnys.

In makeBunnys

In your main, use the special array initialization to create an array of at least 5 Strings. Pass this to makeBunnys,  using showBunnys to print the result.


Part B

Create a class BunnyFarmer  representing a farmer who owns Bunnys. Give it an instance variable name.

Add another instance variable that is an array of Bunnys, bunnyList. You may omit the accessor and mutator, since we often do not provide them for arrays.  In this case, we don't need to keep track of the first empty spot.

Add a default constructor that sets the farmer up with a default name and an array of size 10 with 10 Bunnys in it, each created using the Bunny default constructor (they will all have the same name, etc).

Add a parameterized constructor that takes a name for the farmer and an int for the size of the array.  Set up the array to be that size and fill it with Bunnys, who are named based on the farmer's name and their position in the array, e.g. if the farmer is named Bob they would be "Bob's Bunny 0", "Bob's Bunny 1", Bob's Bunny 2" etc.

Create a toString, which puts the farmer's name at the top and then lists all the Bunnys.

  Add a method pickFavorite() which randomly chooses and returns one Bunny from the array.  (You may instead name this method pickDinner()) 

Back in the main, create an array of three BunnyFarmers, one with the default and two with the parameterized constructor.    In a loop, for each BunnyFarmer print it out  and then have it pick a bunny, and print that as well.


[EC] To BunnyFarmer add a parameterized constructor that takes both a name and an existing array of Bunnys  Set the name and then set bunnyList up as a new empty array of the same size as the array passed in, and then copy the Bunnys one by one from that array to bunnyList.  In main, include in your array a BunnyFarmer made with this constructor, passing in an array of Bunnys you made using makeBunnies.