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.
public abstract class Pet {
private String myName;
public Pet(String name) {}
public String getName() {}
public abstract String speak();
}
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 speak method.
public class Cat extends Pet {
public Cat(String name) {
super(name);
}
public String speak() {
return "meow";
}
}
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 Pet
.
public class LoudDog extends Dog {
public LoudDog(String name) {
super(name);
}
public String speak() {
return super.speak() + super.speak();
}
}
Like Cat
we had to call super
in the constructor to set myName
.
In the speak
method we call super.speak()
because the problem specifies that a LoudDog
should speak two copies of whatever a normal Dog
does.
This time they’re checking that you understand polymorphism. You need to understand that everything in the petList
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.
public void allSpeak() {
for (Object o: petList) {
Pet p = (Pet)o;
p.speak();
}
}
Since petList
is defined as an ArrayList
of 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.