Pet is #2 from the from the 2004 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/apc/ap04_frq_compsci_a_35988.pdf

Part (a) Cat class

public class Cat extends Pet
{
    public Cat(String name)
    {
        super(name);
    }

    public String speak()
    {
        return "meow";
    }
}

See Class writing order for a technique to respond to AP CS FR that request an entire class.

See Inheritance and polymorphism for details including how to write subclasses.

Part (b) LoudDog class

public class LoudDog extends Dog
{
    public LoudDog(String name)
    {
        super(name);
    }

    public String speak()
    {
        return super.speak() + super.speak();
    }
}

Part (c) allSpeak method

public void allSpeak()
{
    for(int i = 0; i < petList.size(); i++)
    {
        Pet p = (Pet) petList.get(i);
        System.out.println(p.getName() + " " + p.speak());
    }
}

On the 2004 AP CS A Exam, the ArrayList get method returned a reference of type Object. It was necessary to cast the reference to the correct type to call most methods. If this question appeared on a more recent AP CS A Exam, petList would have been declared as ArrayList<Pet> petList and casting would not have been required.

The 2004 AP CS A Exam did not feature enhanced for loops.

2004 AP CS A Exam Free Response Solutions

Additional inheritance & polymorphism resources

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Pet

2024-02-29 comment

On part c where is the pet list declared?

Response

petList is declared as an instance variable in Kennel. Method allSpeak is an instance method of Kennel, so it has access to the instance variables.