ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Shape {
    protected String name = "Shape";
    Shape() { System.out.print(name + " "); }
}
class Circle extends Shape {
    Circle() { super(); name = "Circle"; System.out.print(name); }
}
// in main:
new Circle();
  1. A. Shape Circle
  2. B. Circle Circle
  3. C. Shape Shape
  4. D. Circle Shape

Correct answer: A. Shape Circle

Shape's constructor runs first and prints the field's value AT THAT TIME, which is still its own default "Shape" (Circle hasn't reassigned it yet). Only after super() returns does Circle's body reassign name to "Circle" and print it, giving "Shape Circle".

More OOP with C++ and Java questions

Exams that ask this topic