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());
}
}- A. 12
- B. 11
- C. 2
- 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
- A Java class's constructor runs this.handle = acquire(); and then later throws an exception before returning. Which statement is correct?
- What is printed? cpp struct N { int v; N(int x) : v(x) { std::cout << "N" << v << " "; } ~N() { std::cout << "~N" << v << " "; } }; int…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B-" +…
- What is printed? java class Box<T> { T value; } // in main: Box<String> b1 = new Box<>(); Box<Integer> b2 = new Box<>()…
- What is printed (assume typical compiler codegen)? cpp struct Base { ~Base() { cout << "~Base "; } }; struct Derived : Base { int buf =…
- What happens when this line is compiled? java List<String>[] arr = new List<String>[10];