ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Parent {
    int bonus() { return 10; }
}
class Child extends Parent {
    static int bonus(int n) { return n + 1; }
}
// in main:
Parent p = new Child();
System.out.println(p.bonus());
  1. A. 11
  2. B. 10
  3. C. Compilation error: bonus(int) in Child cannot hide bonus() in Parent
  4. D. Compilation error: ambiguous method bonus

Correct answer: B. 10

Child.bonus(int) and Parent.bonus() have different signatures (different parameter lists), so they are simply distinct overloads, not an override and not a clash; p.bonus() (no args) matches Parent's instance method, which is overridden by nothing in Child, so it runs Parent's own bonus() returning 10.

More OOP with C++ and Java questions

Exams that ask this topic