This question is taken from the AP Computer Science practice test.
public class Bird
{
public void act()
{
System.out.print("fly");
makeNoise();
}
public void makeNoise()
{
System.out.print("chirp");
}
}
public class Dove extends Bird
{
public void act()
{
super.act();
System.out.print("waddle");
}
public void makeNoise()
{
super.makeNoise();
System.out.print("coo");
}
}
Assume that in a class other than Bird or Dove, the following declaration appears:
Bird pigeon = new Dove();
What is printed as a result of the call pigeon.act()?
I thought the answer would be “fly tweet”, but the textbook says the answer is “chirpa fly coo waddle”. I thought a pigeon could only access methods available in Bird? I got the impression that if a user wants to access methods in Dove, the “dove” should be thrown into Dove.
Will it Bird pigeon = new Bird();give the same result? How about Dove pigeon = new Dove();?