ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
abstract class Shape {
    Shape() { System.out.print(area() + " "); }
    abstract double area();
}
class Sq extends Shape {
    double s = 2;
    Sq() { System.out.print(area()); }
    double area() { return s * s; }
}
// in main:
new Sq();
  1. A. 4.0 4.0
  2. B. 0.0 4.0
  3. C. 0.0 0.0
  4. D. Compile error: abstract call in constructor

Correct answer: B. 0.0 4.0

Shape's constructor runs before Sq's field initialiser, so the overriding area() sees s = 0.0 and prints 0.0. Then s = 2 is set and Sq's constructor prints 4.0. Calling an abstract method from a constructor compiles; it is just dangerous.

More OOP with C++ and Java questions

Exams that ask this topic