The Pet free response question on the 2004 AP Computer Science exam tested that you can work with ArrayLists and also understand how abstract classes work.
You’re starting off with an abstract class called
Pet that looks something like the following.
The constructor and
getName are both implemented in the version you can get from AP. But the implementation isn’t really important for the problem.
The first section asks you to create a
Cat class that extends
Pet and returns
"meow" from the
One thing to notice here is that the constructor calls
super(name) to set the name of the cat. Because
myName is private in
Pet we can’t set it directly.
Part B is similar to A in that you’re creating a subclass. This time though it’s a subclass of
Dog, which is itself a subclass of
Cat we had to call
super in the constructor to set
speak method we call
super.speak() because the problem specifies that a
LoudDog should speak two copies of whatever a normal
This time they’re checking that you understand polymorphism. You need to understand that everything in the
ArrayList is a
Pet, even though it’s also a more specific subclass. And since it’s a
Pet, it much have a
speak method even though we don’t know how it’s implemented.
petList is defined as an
Objects, we can’t just call the
speak method on each element. First we have to cast it as a
Pet, which happens on the first line in the for each loop.