ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
protected int val;
Base(int v) {
val = v;
System.out.print("Base(" + val + ") ");
}
}
class Derived extends Base {
Derived() {
super(compute());
System.out.print("Derived ");
}
static int compute() {
System.out.print("compute ");
return 42;
}
}
public class Main {
public static void main(String[] args) { new Derived(); }
}- A. Base(42) compute Derived
- B. compute Base(42) Derived
- C. Derived compute Base(42)
- D. Compile-time error: cannot call a static method as a super() argument
Correct answer: B. compute Base(42) Derived
Arguments to super(...) are evaluated before the superclass constructor is entered, so compute() runs first, printing compute and returning 42. Then Base(42) runs, printing Base(42). Only after super() fully completes does Derived's own constructor body continue, printing Derived.
More OOP with C++ and Java questions
- What is printed? cpp struct Logger { Logger(string tag) : tag(tag) { cout << "open-" << tag << " "; } ~Logger() { cout << "close-" << tag…
- What is printed? java class A { A() { this(10); System.out.print("A() "); } A(int x) { System.out.print("A(int)=" + x + " "); } } public…
- What is printed? cpp struct Base { Base() { cout << "Base() "; } Base(int x) { cout << "Base(int) "; } }; struct Derived : Base {…
- What is printed? java class Resource { Resource() { System.out.print("open "); throw new RuntimeException("ctor failed"); } void close() {…
- What is printed? cpp struct Base { virtual ~Base() { cout << "~Base "; } }; struct Mid : Base { ~Mid() { cout << "~Mid "; } }; struct Leaf…
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…