Re: Interface instanceof
gk wrote:
interface MyInterface {
}
public class MyInstanceTest implements MyInterface {
static String s;
public static void main(String args[]) {
MyInstanceTest t = new MyInstanceTest();
if (t instanceof MyInterface) {
System.out.println("I am true interface");
} else {
System.out.println("I am false interface");
}
if (s instanceof String) {
System.out.println("I am true String");
} else {
System.out.println("I am false String");
}
}
}
To understand the output, see the Java Language Specification, 15.20.2
Type Comparison Operator instanceof,
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#80289
"At run time, the result of the instanceof operator is true if the value
of the RelationalExpression is not null and the reference could be cast
(?15.16) to the ReferenceType without raising a ClassCastException.
Otherwise the result is false."
(x instanceof Y) effectively asks "Does x currently point to an object
that could also be pointed to by a reference expression of type Y?"
(t intanceof MyInterface) is true because t points to an object, an
instance of MyInstanceTest, that could be pointed to by a reference
expression of type MyInterface.
(s instanceof String) is false because s does not point to any object at
all.
Patricia