Last post we saw multiline strings in Java 13.
Let’s continue with a new topic; improved version of instanceOf operator introduced in Java 14.
Let’s look at the use of instanceOf keyword in checking for the type of an object during runtime.
class Vehicle {} class Car extends Vehicle { public void drive() { System.out.println("Driving car"); } } class Bicycle extends Vehicle { public void ride() {} } public class InstanceOfKeyword { public static void main(String[] args) { Vehicle vObj = new Car(); if(vObj instanceof Car) { Car car = (Car) vObj; car.drive(); } else if(vObj instanceOf Bicycle) { Bicycle bike = (Bicycle)vObj; bike.ride(); } } }
What’s frustrating with the above code is the type-cast of the vehicle object to Car or Bicycle after identifying it’s type using instanceof!
Java 14 changes that, by imparting some pattern matching power to instanceOf like this
Vehicle vObj = new Car(); if(vObj instanceof Car car) { car.drive(); } else if(vObj instanceOf Bicycle bike) { bike.ride(); }
In the new version, instanceOf tests for the type and binds to a variable of the type. In our case car and bike variables are automatically bound to the corresponding Car and Bicycle objects respectively, eliminating the need to type-cast. Cool. Isn’t it?
The scope of the variables are limited to the if-else blocks