ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Shape {
    double area() { return 0; }
    @Override
    public String toString() { return getClass().getSimpleName() + "(area=" + area() + ")"; }
}
class Square extends Shape {
    double side;
    Square(double s) { side = s; }
    @Override
    double area() { return side * side; }
}
// in main:
Shape s = new Square(3);
System.out.println(s);
  1. A. Square(area=9.0)
  2. B. Shape(area=9.0)
  3. C. Square(area=0.0)
  4. D. Shape(area=0.0)

Correct answer: A. Square(area=9.0)

getClass() always returns the object's actual runtime class regardless of the static reference type, so getClass().getSimpleName() gives "Square"; area() dispatches virtually to Square's override (3*3=9.0), giving "Square(area=9.0)".

More OOP with C++ and Java questions

Exams that ask this topic