ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
Base() {
System.out.print("Base-ctor ");
}
static { System.out.print("Base-static "); }
}
class Sub extends Base {
static { System.out.print("Sub-static "); }
Sub() { System.out.print("Sub-ctor "); }
}
public class Main {
public static void main(String[] args) {
System.out.print("start ");
new Sub();
}
}- A. Base-static Sub-static start Base-ctor Sub-ctor
- B. start Base-static Sub-static Base-ctor Sub-ctor
- C. start Base-ctor Sub-ctor Base-static Sub-static
- D. Base-static Sub-static Base-ctor Sub-ctor start
Correct answer: B. start Base-static Sub-static Base-ctor Sub-ctor
main's own body starts running first, printing start. Only when new Sub() is actually reached does the JVM load (if not already loaded) and statically initialise Base then Sub, in superclass-first order, printing Base-static then Sub-static; then object construction runs, Base-ctor then Sub-ctor.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct Mid : Base { }; struct Leaf : Mid { void f() override {…
- What is printed? java public class Main { static class Base { public String toString() { return "Base"; } public boolean equals(Object o)…
- What is printed? cpp template <typename T> T maxVal(T a, T b) { return a > b ? a : b; } int main() { cout << maxVal(3, 7) << " " <<…
- What happens? java interface A { default String id() { return "A"; } } interface B { default String id() { return "B"; } } class D…
- What is printed? cpp struct Base { virtual void f() = 0; void greet() { cout << "greet "; f(); } }; struct Derived : Base { void f()…
- What happens? cpp struct Shape { virtual double area() const = 0; }; int main() { Shape s; cout << s.area(); }