oop
22. Pattern Matching for instanceof
Analyze the code, write your predicted output, and then reveal the solution.
The Scenario
Java 16 introduced pattern matching for instanceof, which simplifies the common "check-then-cast" idiom. This is a significant enhancement to how we handle polymorphism safely.
Predict the output of the following code.
class Shape { } class Circle extends Shape { double radius = 5.0; void info() { System.out.println("Circle"); } } public class Main { public static void main(String[] args) { Object obj = new Circle(); if (obj instanceof Circle c && c.radius > 0) { c.info(); System.out.println(c.radius); } else { System.out.println("Not a positive circle"); } // Scope Check // System.out.println(c.radius); // Will this work? } }
Take Your Shot
Predicted Output
Type exactly what you think will be printed in the console.