Let A be a superclass of AB and AC. Given a method:
public void handleStuff(A someObject) {
if(someObject instanceof AB){
((AB)someObject).someABFunction();
} else if(someObject instanceof AC) {
((AC)someObject).someACFunction();
}
}
I don’t like the double checking/casting operation here; is there any other way to code this without first checking for a type and then casting? I know I could do it with two overloaded functions that take AB or AC as parameters, but I was looking for less code, not more 🙂 Something like:
public void handleStuff(A someObject) {
if(someObject instanceof AB){
someObject.someABFunction(); // it is already clear that this is AB
} else if(someObject instanceof AC) {
someObject.someACFunction(); // it is already clear that this is AC
}
}
>Solution :
On Java 16 and newer, you can use pattern matching to avoid the cast. Like this:
public void handleStuff(A someObject) {
if (someObject instanceof AB ab) {
ab.someABFunction();
} else if (someObject instanceof AC ac) {
ac.someACFunction();
}
}
On Java 17 and newer, you can enable the preview feature for pattern matching in switch-expressions to shorten it further. With that feature, you can do this:
public void handleStuff(A someObject) {
switch (someObject) {
case AB ab -> ab.someABFunction();
case AC ac -> ac.someACFunction();
default -> {}
}
}