Polymorphism

AP Computer Science A· difficulty 3/5

public class Animal {
    public String toString() { return "Animal"; }
}
public class Dog extends Animal {
    public String toString() { return "Dog"; }
}
// Usage:
Object o = new Dog();
System.out.print(o.toString());

What is printed?

  • A

    Compile error

  • B

    Dog

    check_circle
  • C

    Animal

  • D

    Object hashcode

Explanation

toString is defined in Object and overridden by Dog. Dynamic dispatch picks Dog's version regardless of declared type.

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

Related questions