Java Pattern Matching for instanceof is an improvement of the traditional instanceof operator in Java. It got introduced as a preview feature in Java 14.
Usually, we use the traditional instanceof when we have a reference of superclass type, and we need to check the type of that instance and cast appropriately.
Let’s see first one example with old/traditional instanceof operator:
class Test {
public static void main(String[] args) {
Vehicle vehicle = new Car();
if (vehicle instanceof Car) {
Car car = (Car) vehicle;
car.openTrunk();
// other code ...
} else if (vehicle instanceof Truck) {
Truck truck = (Truck) vehicle;
truck.removeTrailer();
// other code ...
}
}
}
In the above example, we test the vehicle object to see if it is of type Car or a Truck. And based on that, we are casting the object, and calling the appropriate method.
With Java Pattern Matching for instanceof, the same logic can be written as below:
class Test {
public static void main(String[] args) {
Vehicle vehicle = new Car();
if (vehicle instanceof Car car) {
car.openTrunk();
// other code ...
} else if (vehicle instanceof Truck truck) {
truck.removeTrailer();
// other code ...
}
}
}
We don’t need to cast the object vehicle to a car explicitly. That will be done for us, and the casted object will be placed in the variable car or truck.
That’s it!