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();- A. Shape Circle
- B. Circle Circle
- C. Shape Shape
- 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
- What is printed? cpp class Account { double balance; public: explicit Account(double b) : balance(b) {} double get() const { return…
- What is printed? java class Base { protected Object clone2() { return new Base(); } } class Sub extends Base { @Override public Object…
- What is printed? java class Shape { double area() { return 0.0; } } class Rectangle extends Shape { double w, h; Rectangle(double w…
- What is printed? java class Vehicle implements Comparable<Vehicle> { int speed; Vehicle(int s) { speed = s; } public int compareTo(Vehicle…
- What is printed? cpp struct Base { virtual Base& self() { cout << "Base::self "; return this; } }; struct Derived : Base { Derived& self()…
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…