ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
class A {
    protected int val() { return 1; }
}
class B extends A {
    protected int val() { return 2; }
}
class C extends B {
    protected int val() { return super.val() + 10; }
}
public class Main {
    public static void main(String[] args) {
        A obj = new C();
        System.out.print(obj.val());
    }
}
  1. A. 12
  2. B. 11
  3. C. 2
  4. D. 1

Correct answer: A. 12

obj.val() dispatches to C's override (dynamic type is C). C's val() calls super.val(), which explicitly means B's version (not A's — super always refers to the immediate parent class in the source, not grandparents), returning 2, plus 10 = 12.

More OOP with C++ and Java questions

Exams that ask this topic