The pattern matching in Java 17 reduces the boilerplate code by removing the convertion step.
What interesting is the extended scope of pattern created variable. The function whatIsIt1 has a if block, but the airplane and ship variables are extended out of if scope.
import java.time.LocalDate;
public class App {
public static void main(String[] args) {
var app = new App();
var t1 = new Titanic();
var b1 = new Boing();
app.whatIsIt(t1);
app.whatIsIt(b1);
app.whatIsIt1(t1);
app.whatIsIt1(b1);
}
public void whatIsIt(Object obj) {
if ( obj instanceof Airplane airplane )
System.out.println(airplane.name);
else if (obj instanceof Ship ship ) {
System.out.println(ship.name);
}
else
System.out.println("I Don't Know");
}
public void whatIsIt1(Object obj) {
if ( !(obj instanceof Airplane airplane)) {
if ( !(obj instanceof Ship ship )) {
System.out.println("I Don't Know");
return;
}
System.out.println(ship.name);
return;
}
System.out.println(airplane.name);
}
static class Airplane {
public String name = "Airplane";
}
static class Ship {
public String name = "Ship";
}
static class Boing extends Airplane {
}
static class Titanic extends Ship {
}
}