Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal { public String s() { return "?"; } }
public class Dog extends Animal { public String s() { return "Woof"; } }
public class Cat extends Animal { public String s() { return "Meow"; } }
Animal[] arr = { new Dog(), new Cat(), new Animal() };
for (Animal a : arr) System.out.print(a.s() + " ");

What is printed?

  • A

    Woof Meow ?

    check_circle
  • B

    Woof Woof Woof

  • C

    ? ? ?

  • D

    Compile-time error

Explanation

Each element invokes its actual class's s() method.

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

Related questions