Tracing instanceof tests in a shape loop

A Java geometry program defines these classes:


Java
class Shape { }
class Rect extends Shape {
    int w, h;
    Rect(int w, int h) { this.w = w; this.h = h; }
}
class Square extends Rect {
    Square(int side) { super(side, side); }
}
class Circle extends Shape {
    int r;
    Circle(int r) { this.r = r; }
}


Its main method runs:


Java
Shape[] shapes = { new Square(3), new Rect(2, 5), new Circle(4), new Square(2), new Rect(1, 6) };
int total = 0;
for (Shape s : shapes) {
    if (s instanceof Rect r) {
        total += r.w * r.h;
    } else if (s instanceof Square sq) {
        total += 10 * sq.w;
    } else if (s instanceof Circle c) {
        total += c.r;
    }
}
System.out.println(total);


What value does the program print? Give the answer as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Type Conversion and Casting Questions: