Difference between ‘instanceof’ and Class.isAssignableFrom(…)

Sometimes it is necessary to determine the ownership of a specific instance of a class to a hierarchy of inheritance, as well as belonging to implement a specific interface. In Java, there are several approaches to solving this problem, from which we draw attention to the distinction between using the instanceof operator and Class.isAssignableFrom (Class <?> Cls) method. One of the main differences is that the use of instanceof operator can detect errors at compile time.

Sample code that allows to identify compile-time error:

While the code presented below, would be executed without any errors:

Thus, instanceof operator is useful when you clearly know what the class inheritance hierarchy is involved and what interfaces it implements, otherwise appropriate to look toward Class.isAssignableFrom (Class <?> Cls) methods which in turn allows for more flexible code, which provides the possibility of composition.