Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
How does 'instanceof' work with interface?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: How does 'instanceof' work with interface?

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";  
    System.out.println(obj instanceof MyInterface); // false, but legal
    System.out.println(s instanceof MyInterface);   // compiler error, String is final class
  }
}

 

References

Why can any non-final class be casted to an interface?
5.5 Casting Conversion

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help