--
An instanceof interface expression always allowed at compile time if the left hand of instance's class is not defined as final class. If the compiler can determine at compile time that the left hand side can never be casted to the interface, that's a compile time error. If the class is not a
final
class, the compiler can not determine what interfaces are implemented by it. Even if the class does not implement the interface, but one of its subclass might. If the actually object class does not implement the interface
then you will get "false" at runtime.interface MyInterface {} class MyObject {} public class Program { public static void main(String[] args) { MyObject obj = new MyObject(); String s = "hello"; // false, but legal System.out.println(obj instanceof MyInterface); // compiler error, String is final class System.out.println(s instanceof MyInterface); } }
Comments
Post a Comment