ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Shape {
    double area() { return 0; }
}
class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }
    @Override
    double area() { return Math.PI * radius * radius; }
}
// in main:
Shape[] shapes = { new Shape(), new Circle(2) };
double total = 0;
for (Shape s : shapes) total += s.area();
System.out.printf("%.2f", total);
  1. A. 0.00
  2. B. 12.57
  3. C. Compile-time error: Shape[] cannot hold a Circle
  4. D. 4.00

Correct answer: B. 12.57

An array of the base type can freely hold subtype objects. The plain Shape contributes area() = 0; the Circle's overridden area() runs polymorphically, contributing pi*2*2 ≈ 12.566..., so the total prints as 12.57.

More OOP with C++ and Java questions

Exams that ask this topic