When you make the Bat final class, you say that this class cannot be subclassed. Since Bat does not implement the Flyer interface, the compiler can determine that b instanceof Flyer never be true and causes an error.
This is indicated in the JLS section 15.20.2 :
If the listing (ยง15.16) of the RelationalExpression for ReferenceType is rejected as a compile-time error, then the instanceof relational expression also throws a compile-time error. In such a situation, the result of the instanceof expression can never be true.
In addition, from section 15.16 on expression expressions:
This is a compile-time error if the instance type of the compilation type can never be applied to the type specified by the casting operator in accordance with casting conversion rules (ยง5.5).
In this case, Bat never be applied to Flyer : it does not implement it, and final guarantees that there cannot be subclasses that implement it.
As you learned, corrections:
- Make a
Bat implementation of Flyer : in this case, the instanceof operator will always return true . - Remove the
final identifier, implying that there may be subclasses of the Bat implementation of the Flyer .
source share