Skip to main content

Posts

Showing posts with the label instanceof

How does 'instanceof' work with interface?

-- 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); } }

What is 'instanceof'?

The instanceof operator is used to check whether the run-time type of an object is compatible with a given type ( 15.20.2 Type Comparison Operator instanceof ):   expression instanceof type The type of an expression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The type mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs. An instanceof expression evaluates to true if both of the following conditions are met: expression is not null . expression can be cast to type . That is, a cast expression of the form (type)(expression) will complete without raising a ClassCastException . It is a compile-time error if the type mentioned after the instanceof operator does not denote a reifiable type . If a cast of the expression to the type would be rejected as a compile-time error, then the instanceof relational expression likewise produces a c...