Methods Practice


Part A

Write a class Gorilla. Gorillas should have a name and a weight. name cannot be null, weight cannot be negative.

In addition to the standard methods, add a parameterized constructor that takes values for name and weight as parameters and sets the instance variables accordingly.

Part B

Create a class Cat. Cats should have a name and a color (both Strings).

In addition to the standard methods, also add a parameterized constructor that takes a value for the name.

Part C

Add to the Gorilla class an instance variable of type Cat, called pet .

(Do not use new to create a new cat in the default Gorilla constructor, unless you are prepared to argue that every time a baby gorilla is born, a kitten magically appears with it.)

Add an accessor and mutator for the pet variable.

☑ update toString so that it includes something like " and a pet kitten, Fluffy" if the Gorilla has a pet but doesn't mention pets if there is no pet yet (what value would pet have if it hasn't been set to any Cat yet?)

☑Give the Cat class an instance variable ape, of type Gorilla, and add mutator and accessor for it.

☑In the Gorilla class, add a method adopt which takes a Cat, and (if the Cat isn't null) sets the Gorilla's pet to that Cat, and the Cat's ape to the Gorilla.

☑In the Gorilla class, add a method swap, which takes a Gorilla, and if that Gorilla is not null, and both Gorilla's have pets, swap pets with the other gorilla. ☑To the Gorilla class, add a parameterized constructor that takes a String and a Cat, and sets the Gorilla's name and pet accordingly. We would usually use the mutators to do this, but we want to make sure that the new pet knows whose ape they are, so think about what method would achieve this.

[EC] To the Gorilla class, add a parameterized constructor that takes two Strings. The first is the name of the Gorilla. The second will be the name of the pet Cat. In this constructor, use the parameterized constructor for the Cat class to set up the pet variable so that it points to a newly created Cat, using the given second string for the name. So in this case calling the Gorilla constructor will also cause a Cat to be created on the heap.