ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
class A {
    void f() { System.out.print("Af "); g(); }
    void g() { System.out.print("Ag "); }
}
class B extends A {
    void f() { System.out.print("Bf "); super.f(); }
    void g() { System.out.print("Bg "); }
}
// in main:
new B().f();
  1. A. Bf Af Bg
  2. B. Bf Af Ag
  3. C. Af Bg
  4. D. Bf Bg

Correct answer: A. Bf Af Bg

super.f() runs A's body statically, but inside it g() is an ordinary virtual call on the same B object, so B's g runs. This is the template-method pattern.

More OOP with C++ and Java questions

Exams that ask this topic