ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Animal {
    String category() { return "Animal"; }
}
class Mammal extends Animal {
    @Override
    String category() { return "Mammal:" + super.category(); }
}
class Dog extends Mammal {
    @Override
    String category() { return "Dog:" + super.category(); }
}
// in main:
Animal a = new Dog();
System.out.println(a.category());
  1. A. Dog:Mammal:Animal
  2. B. Animal:Mammal:Dog
  3. C. Dog
  4. D. Mammal:Animal

Correct answer: A. Dog:Mammal:Animal

a.category() dispatches virtually to Dog's override, which prepends "Dog:" to super.category() (Mammal's), which itself prepends "Mammal:" to super.category() (Animal's, "Animal"): building "Dog:Mammal:Animal" from the inside out.

More OOP with C++ and Java questions

Exams that ask this topic