ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class Animal { String speak() { return "animal"; } }
class Dog extends Animal { String speak() { return "dog"; } }
// static methods of the main class:
static String m(Animal a) { return "A"; }
static String m(Dog d)    { return "D"; }
// in main:
Animal a = new Dog();
System.out.print(m(a) + "-" + a.speak());
  1. A. D-dog
  2. B. A-animal
  3. C. D-animal
  4. D. A-dog

Correct answer: D. A-dog

Overload choice uses the compile-time type of the argument, Animal, so m(Animal) runs: A. The overridden speak is chosen at run time from the real object, a Dog: dog.

More OOP with C++ and Java questions

Exams that ask this topic