Setup
Consider a class Creature for creatures that have a
name,
can speak, and can act and a
main
method that creates four Creatures and has each
act
five times:
public class Creature {
protected String name; // Creature's name
// constructor: initialize name to n
public Creature(String n) {
name = n;
}
// speak, i.e. vocalize
public void speak() {
System.out.println(name + " speaks");
}
// perform an action
public void act() {
speak();
}
}
// create 4 Creatures and repeatedly (5 times)
// have each act one at a time
public class CUCSApplication {
public static void main(String args[]) {
Creature[] c = { // 4 Creatures
new Creature("Butch"),
new Creature("Fluffy"),
new Creature("Sleepy"),
new Creature("Clarus")
};
// repeat 5 times: each Creature acts
for (int times=5; times>0; times--)
for (int i = 0; i<c.length; i++)
c[i].act();
}
}
(Observe the use of an array to reduce redundancy.)
What To Do
Compile and run the given code to see the behavior of the generic
Creature.
Define the following sub-classes and define/override methods as specified:
-
Class Cat is a sub-class of Creature, with
members:
-
Integer field purrLength: the ``purr length'' of a Cat
(see purr below). Assume purr lengths are at least 2.
-
Method speak: ``meow'' instead of ``speak'', i.e. print
the name of the Cat and then print ``meows'', e.g. Fluffy meows.
-
Method purr: ``purr'' with the specified ``purr length''
number of r's, e.g. Sleepy purrrrrs has purr length 5.
-
Method act: randomly (50-50) choose between the original
act of a Creature and the new action purr.
Write your code so that if Creature.act were changed, then
Cat.act would inherit the changes.
-
Class Dog is a sub-class of Creature, with
members:
-
Integer field wags: how many times the dog has wagged its
tail.
-
Method speak: ``woof'' instead of ``speak''.
-
Method wag: ``wag'' and print how many times the dog has
wagged its tail, e.g. Butch wags its tail for the 1-th time.
-
Method act: (like Cat.act) randomly (50-50)
choose between the original act of a Creature
and the new action wag.
-
Class DogCow is a sub-class of Dog, with
members:
-
Every DogCow is named ``Clarus''. (This does not involve
static.)
-
Method speak: randomly (50-50) choose between how a dog
(normally) speaks and saying ``moof''.
-
Modify method main to make a Dog ``Butch'', a Cat ``Fluffy''
with purr length 3, a Cat ``Sleepy'' with purr length 7, and a DogCow ``Clarus''.
The method should still have each Creature act 5 times.
-
Use good style and use super appropriately! You should
use super as appropriate to invoke the constructor of super-classes
and to invoke behavior of super-classes.
-
Thought question --make sure you understand, but don't turn in an answer--
what does it mean for field name to be protected,
i.e. what is its scope?
Turn in a printout of your Java code for Creature, Cat, Dog, DogCow, and
the main method, and a printout of the output from main.