Java
Pattern matching
Learn type conversion with instanceof pattern matching.
Type checking with instanceof
Sometimes you need to know the actual type of a polymorphic reference. The instanceof operator does this: if (s instanceof Circle) is true when s is really a Circle. In older Java you had to cast and store a separate variable.
Since Java 16, pattern matching for instanceof exists: if (s instanceof Circle c) automatically casts s to Circle as c. It is shorter and safer.
Switch patterns (Java 21)
Since Java 21, switch expressions can test types. Writing switch (s) { case Circle c -> ...; case Square q -> ...; } runs different code for each type. This is more readable than a chain of if-instanceof.
The switch expression can return a value; case null handles null. If subclasses are not all covered, a default is required.
Exercise Print a field with pattern matching
Use the abstract class Shape and Circle extends Shape from above. Add class Square extends Shape with int side, a constructor and an area method returning side * side. In main, assign Shape s = new Circle(3);, then use if (s instanceof Circle c) pattern matching to print System.out.println("Circle: " + c.r);.
Show example solution
abstract class Shape {
abstract int area();
}
class Circle extends Shape {
int r;
Circle(int r) { this.r = r; }
int area() { return r * r * 3; }
}
class Square extends Shape {
int side;
Square(int side) { this.side = side; }
int area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(3);
if (s instanceof Circle c) {
System.out.println("Circle: " + c.r);
}
}
}
Test yourself
-
Complete the pattern matching
if (s instanceof ____ c) {
System.out.println(c.r);
}
Show answer
if (s instanceof Circle c) {
System.out.println(c.r);
}
-
What does instanceof Circle c do?
- Casts c to Circle and defines it in scope
- Makes c a static variable
- Removes the Circle class
- Converts Shape into Circle
Show answer
Casts c to Circle and defines it in scope — If the type check passes, pattern matching binds c as Circle.
-
Match the instanceof concepts
- instanceof
- Type check operator
- pattern matching
- Binds the cast automatically
- switch (Java 21)
- Type-based branching
- default
- Required when not all types covered
Next lesson: Summary - Polymorphism