Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal {
    public String sound() { return "?"; }
}
public class Dog extends Animal {
    public String sound() { return "woof"; }
}
public class Cat extends Animal {
    public String sound() { return "meow"; }
}
// Usage:
Animal[] arr = {new Dog(), new Cat(), new Animal()};
for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i].sound() + " ");
}

What is printed?

  • A

    ? ? ?

  • B

    Compile error

  • C

    woof woof woof

  • D

    woof meow ?

    check_circle

Explanation

Each call uses dynamic dispatch based on actual type: Dog says "woof", Cat says "meow", and the plain Animal returns "?".

Want 10 more like this — adaptive to your weak spots?

Related questions