ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base {
    protected String name() { return "Base"; }
    public String greet() { return "Hi " + name(); }
}
class Child extends Base {
    protected String name() { return "Child"; }
}
// in main:
Base b = new Child();
System.out.println(b.greet());
  1. A. Hi Base
  2. B. Hi Child
  3. C. Compile-time error: greet() cannot call a protected method of another class
  4. D. Hi null

Correct answer: B. Hi Child

greet() is inherited unchanged by Child, but the call to name() inside it is dynamically dispatched: since b's runtime type is Child, Child.name() runs, returning "Child", so greet() prints "Hi Child". This is the template-method pattern relying on polymorphism.

More OOP with C++ and Java questions

Exams that ask this topic