| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
How does 'instanceof' work with interface?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
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
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
}
}
ReferencesWhy can any non-final class be casted to an interface?5.5 Casting Conversion |