
🗼 Java Pattern Matching with instanceof
— Paris Monuments Edition
Pattern matching in Java lets you check whether an object fits a specific structure (like a class), and if it does, automatically extract information from it. It improves clarity, safety, and reduces boilerplate code — especially when used with the instanceof operator.
Introduced officially in JEP 394, pattern matching for instanceof is available from Java 16 onwards.
🧠 What Is Pattern Matching?
Traditionally, when you wanted to work with a specific subtype of an object, you needed to:
1️⃣ Test the type with instanceof
2️⃣ Cast it to the target class
3️⃣ Use its specific fields or methods
Let’s illustrate this with a theme of Paris monuments! We'll model some famous landmarks with a Monument interface.
🏛️ Traditional instanceof Usage
This code works but requires explicit casting, which is repetitive and error-prone.
✨ Enter Pattern Matching
Pattern matching lets you streamline the code and safely access subclass data without casting:
Notice how we:
🟣 Test the type
🟣 Declare a variable (e or a) of the right type
🟣 Access the data without casting
✅ Shorter, cleaner, safer.
🧩 Breakdown of a Pattern
Consider this pattern:
It consists of:
🟣 Predicate: instanceof EiffelTower – checks the type
🟣 Target: m – the object being tested
🟣 Pattern variable: e – available if the test passes
🧭 Scope of Pattern Variables
Pattern variables (like e and a) only exist when the instanceof check is true.
They can also be used directly in complex conditions:
But be careful — this is not allowed:
📌 Summary
Pattern matching with instanceof:
🟣 Reduces casting
🟣 Makes your code cleaner and more maintainable
🟣 Prevents accidental bugs due to mismatched types
🟣 Is especially helpful when working with complex object models — or iconic monuments!