ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Shape {
    double scale = 1.0;
    double area() { return 0; }
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override
    double area() { return Math.PI * r * r * scale; }
}
public class Main {
    public static void main(String[] args) {
        Circle c = new Circle(2);
        c.scale = 2.0;
        Shape s = c;
        System.out.printf("%.2f", s.area());
    }
}
  1. A. 12.57
  2. B. 25.13
  3. C. 6.28
  4. D. Compile-time error: scale is not visible through a Shape reference's area()

Correct answer: B. 25.13

scale is a regular inherited field, shared between the Shape view and the Circle object (there's only one scale value per object, not per reference type). Setting c.scale = 2.0 mutates the actual object; s.area() dispatches to Circle's override, which reads that same scale, computing pi*2*2*2.0 ≈ 25.13.

More OOP with C++ and Java questions

Exams that ask this topic