ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Shape {
    double area() { return 0.0; }
}
class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    @Override
    double area() { return w * h; }
}
class Square extends Rectangle {
    Square(double s) { super(s, s); }
}
public class Main {
    public static void main(String[] args) {
        Shape s = new Square(4);
        System.out.println(s.area());
    }
}
  1. A. 0.0
  2. B. 4.0
  3. C. 16.0
  4. D. Compile-time error: Square must override area() itself

Correct answer: C. 16.0

Square does not override area(); it simply inherits Rectangle's implementation, which uses w and h set via super(s, s), both 4. Dynamic dispatch on s (actually a Square) finds the nearest implementation up the chain, Rectangle.area(), returning 4*4 = 16.0.

More OOP with C++ and Java questions

Exams that ask this topic