Class Methods - Practice


Class Methods

Bunny.java
BunnyTestHarness.java

read ch. 6, 8, start ch 7


From now on, every class that has instance variables should have at least one constructor, and all instance variables should be private and always have accessors and mutators (you already know there should be a toString) unless specified otherwise.


Classwork


Part A

☑ Create a class Cat, with a name, which cannot be null, a weight, which cannot be 0 or negative, and a boolean for whether it is hungry. In addition to the usual methods, give Cat a parameterized constructor that takes name and weight.

☑ Create a class Gorilla, with a name, which cannot be null, and an age, which cannot be negative, and a pet, which is a Cat.

The pet should start as null (baby gorillas don't automatically have pets) but should not be able to be set back to null later. Also, kittens under 1 pound are too small to be pets. If the gorilla doesn't yet have a pet, don't mention it in the toString, but do give its information if they do.

☑ In a main, create gorillas and cats and make sure you can set their instance vars and print them


Part B

☑ Give Gorilla a parameterized constructor that takes a name, and an age.

☑ Give Gorilla a parameterized constructor that takes a name, an age, and a Cat. Chain back to the parameterized constructor you just wrote.

☑ Give Gorilla a parameterized constructor that takes a name, an age, and also a name and weight for a Cat. Chain back to the parameterized constructor you just wrote.

☑ Give Gorilla a method play which reports that it is playing with its pet, or else playing alone if it doesn't have one. If it plays with the pet, the pet becomes hungry

☑ Give Gorilla a method feedPet which, if the pet is hungry, reports that it is feeding the pet, which increases the pet's weight by .2 pounds and makes the pet no longer hungry. Also report what is happening if there is no pet, or the pet isn't hungry.

☑ In main, make sure you can create Gorillas with each of the types of constructor, and that they can play and feed.