The cast is ok because you are
testing for non-final class and at runtime some derived class of P may implement the interface R .
for e.g.
but if you declared your class P as final like
So in a nutshell for final class the compiler is sure whether the class implements interface or not but for non-final class compiler cannot be sure and that's why cast is allowed.