ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Base {
    protected int code() { return 1; }
}
class Mid extends Base {
    @Override
    protected int code() { return super.code() + 10; }
}
class Leaf extends Mid {
    @Override
    protected int code() { return super.code() + 100; }
}
public class Main {
    public static void main(String[] args) { System.out.println(new Leaf().code()); }
}
  1. A. 1
  2. B. 11
  3. C. 111
  4. D. 100

Correct answer: C. 111

Leaf.code() calls super.code(), reaching Mid's override (statically, one level up from Leaf), which itself calls super.code(), reaching Base's version (one level up from Mid), returning 1. Mid adds 10, giving 11; Leaf adds 100 to that, giving 111.

More OOP with C++ and Java questions

Exams that ask this topic