Polymorphism

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 Zoo {
    public static String hear(Animal a) { return a.sound(); }
}
// Usage:
System.out.print(Zoo.hear(new Dog()));

What is printed?

  • A

    Animal

  • B

    Compile error

  • C

    ?

  • D

    woof

    check_circle

Explanation

A method that takes Animal can accept any subclass. Dynamic dispatch invokes Dog's sound, returning "woof".

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

Related questions