Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Replace this type-check chain with polymorphism and explain the benefit:

Java
double area(Shape s) {
if (s instanceof Circle c) return Math.PI * c.r() * c.r();
else if (s instanceof Square q) return q.side() * q.side();
throw new IllegalArgumentException();
}

Declare double area() on Shape and implement it in Circle and Square, so callers simply write s.area() and the JVM picks the right implementation. Adding a shape then means adding one class instead of editing every type-check chain. As an alternative, with a sealed Shape and a pattern-matching switch, the compiler checks that every case is handled; polymorphism suits open sets of types with shared behaviour, while pattern matching suits closed sets where new operations are added often.

Why this question is asked

Chains of instanceof checks are one of the most common smells in object-oriented code. They look harmless with two shapes, but every new type means finding and editing every chain, and a missed one only fails at run time with an exception. Interviewers ask this refactoring question to see whether we can apply polymorphism, and the strongest answers also know modern Java's alternative, sealed types with pattern matching, and when each is the better choice. In this answer, we will look at what is wrong with the chain, refactor it to polymorphism, add a new shape to see the benefit, then write the sealed version and compare the two.

1What Is Wrong With the Type-Check Chain

The original code asks the object what it is and then decides what to do. Here is the code with records for the shapes, which match the r() and side() accessors in the question.

Java
interface Shape { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }
double area(Shape s) {
if (s instanceof Circle c) return Math.PI * c.r() * c.r();
else if (s instanceof Square q) return q.side() * q.side();
throw new IllegalArgumentException("unknown shape " + s);
}
area(new Circle(1)); // 3.141592653589793
area(new Square(2)); // 4.0
area(new Triangle(3, 4)); // IllegalArgumentException at run time

Notice the last line. When someone adds a Triangle, the compiler says nothing, and the program fails only when a triangle reaches this method. In a real code base the same chain often appears in several places, area, perimeter, rendering, export, and each one must be found and updated by hand. The knowledge of what a circle is gets spread across the code instead of living in Circle.

2Refactoring to Polymorphism

Polymorphism means that one call, s.area(), runs different code depending on the object's actual class. We declare the operation on the Shape type and let each class implement it.

Java
interface Shape {
double area();
}
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
}
List<Shape> shapes = List.of(new Circle(1), new Square(2));
double total = 0;
for (Shape s : shapes) total += s.area(); // the JVM picks Circle.area or Square.area
System.out.println(total); // 7.141592653589793

The caller no longer knows or cares which shapes exist. It calls area() and dynamic dispatch, the run-time selection of the method from the object's class, chooses the right implementation. Notice that each formula now lives next to the data it uses: Circle owns r and the circle formula, Square owns side and the square formula. The method in records must be public because it implements an interface method, which is implicitly public.

3Adding a New Shape

The benefit shows up when the set of types grows. Adding a triangle is now one new class, and nothing else in the code base changes.

Java
record Triangle(double base, double height) implements Shape {
public double area() { return 0.5 * base * height; }
}
System.out.println(new Triangle(3, 4).area()); // 6.0
// forgetting area() is a compile error: Triangle is not abstract and does not override area()

Notice the comment. With polymorphism, forgetting to implement the operation is caught by the compiler, because Shape declares area() as abstract. With the instanceof chain, forgetting a case was caught only in production. This is the open/closed idea in practice: the code that uses shapes is closed for modification but open for extension with new types.

4The Alternative: A Sealed Shape and a Pattern Switch

Since Java 21, there is a second good answer. A sealed interface lists exactly which classes may implement it. A switch over a sealed type with record patterns then lets us write the operation in one place, and the compiler checks that every permitted type is handled, so no default branch is needed.

Java
sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
}; // no default needed: the compiler knows these are all the cases
}
System.out.println(area(new Square(3))); // 9.0
// adding Triangle to permits makes this switch fail to compile until a case is added

This version keeps the type-based structure of the original but fixes its weakness. The throw at the end is gone because it can never happen, and adding a new shape to the permits clause turns every switch that does not handle it into a compile error, which is a precise to-do list. Notice what is easy here: adding a new operation, such as perimeter, is one new method with one switch, without touching the shape records.

5Choosing Between the Two

The two designs make opposite things easy. With polymorphism, adding a type is one class, but adding an operation, say perimeter or toSvg, means editing every class. With a sealed type and pattern switches, adding an operation is one method, but adding a type means editing every switch, with the compiler pointing to each one. This trade-off is known as the expression problem.

So the choice follows what changes more often. If the set of types is open, other modules or teams add shapes, and the operations are a stable core like area, polymorphism is the better fit. If one team owns a closed set of types, such as the variants of a domain event or an expression tree, and new operations are added often, a sealed hierarchy with pattern matching is clearer. For this question, the simplest refactoring is to put area() on Shape, and the sealed switch is a strong alternative if the shapes are fixed.

Polymorphism versus sealed types with pattern switches
QuestionPolymorphism (area() on Shape)Sealed type + switch
Add a new shapeone new classedit every switch (compiler lists them)
Add a new operationedit every shape classone new method
Missing case caughtat compile time (abstract method)at compile time (exhaustive switch)
Logic livesinside each typein one place per operation
Best whentypes are open, operations stabletypes closed, operations change often

6Follow-up questions

Is instanceof always a code smell?

No. Pattern matching with instanceof is fine at system edges, for example when handling an exception type or an object from an untyped source, and in equals methods. It becomes a smell when the same type-check chain over our own domain types appears in several places, because that duplicates knowledge that belongs in the types and fails silently when a new type appears.

Could we use an enum instead?

Yes, if shapes had no per-instance data. An enum with an abstract area method and a body per constant is a closed set with polymorphism. Since circles and squares carry their own dimensions, records implementing an interface, sealed or not, are the better model here.

Does the switch version lose performance compared with virtual calls?

Not in a way that matters for normal code. Both compile to a type check and a jump, and the JIT optimises common cases in both. The choice should be made on design grounds: which kind of change we expect.

7Conclusion

In this answer, we replaced an instanceof chain, which spreads type knowledge around and fails at run time when a new type appears, with an area() method declared on Shape and implemented in Circle and Square. Adding a Triangle became one class, and forgetting the method became a compile error. We then wrote the sealed alternative, where an exhaustive pattern switch is checked by the compiler, and saw the trade-off: polymorphism makes new types easy, while sealed types with switches make new operations easy, so the choice follows which one changes more often.

What to say in the interviewAbout 90 seconds aloud

Open with

I would declare double area on the Shape interface and implement it in each shape, so Circle returns pi r squared and Square returns side squared, and the caller just calls s.area.

Then, if they want more

Dynamic dispatch picks the right implementation at run time. The benefit is that knowledge about each shape lives in that shape's class instead of in type-check chains scattered around the code.

Adding a Triangle means writing one new class, and if I forget area, the compiler tells me, whereas with the instanceof chain the new shape would only fail at run time with that IllegalArgumentException, and I would have to find every chain by hand.

In modern Java there is also a good alternative: make Shape a sealed interface that permits Circle and Square, and write area as a switch with record patterns. The compiler knows the full set of cases, so the switch needs no default, and adding a new permitted shape makes every incomplete switch a compile error.

The two styles trade off in opposite directions. Polymorphism makes adding new types easy and new operations harder, while sealed types with pattern switches make adding operations easy and new types harder.

So I would use polymorphism when the set of shapes is open or extended by others, and sealed types when one team owns a closed set and keeps adding operations.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Replace this type-check chain with polymorphism and explain the benefit:": https://scrivio-interview-library.netlify.app/java/oop-principles/608119f2c7/