178. Hooking sealed classes and instanceof
Sealed classes influence how the compiler understands the instanceof
operator and, implicitly, how it performs internal cast and conversion operations.
Let’s consider the following snippet of code:
public interface Quadrilateral {}
public class Triangle {}
So, we have here an interface (Quadrilateral
) and a class that doesn’t implement this interface. In this context, does the following code compile?
public static void drawTriangle(Triangle t) {
if (t instanceof Quadrilateral) {
System.out.println("This is not a triangle");
} else {
System.out.println("Drawing a triangle");
}
}
We wrote if (t instanceof Quadrilateral) {…}
but we know that Triangle
doesn’t implement Quadrilateral
, so at first sight, we may think that the compiler will complain about this. But, actually, the code compiles because, at runtime, we may have a class Rectangle
that extends Triangle...