带有接口的 Java 中的运算符实例



谁能用实例运算符解释Java中的以下行为。

Runnable r = new Thread();

即使变量 r 的类型是可运行的,并且比较实例是在不驻留在相同类层次结构中的类上完成

System.out.println(r instanceof String); // This line does not compile 
System.out.println(r instanceof Vector); // This line compiles
System.out.println(r instanceof FileNotFoundException); // This line compiles

String类是final的——这意味着它不能被子类化。此外,它不实现Runnable.所有这些都在编译时是已知的;因此,编译错误。

一个例子:

static class First {
}
static final class Second {
}

比 :

Runnable r = new Thread();
System.out.println(r instanceof First);
System.out.println(r instanceof Second);

编译器看到Secondfinal的,因此它不能有任何sub-classes,因此它不能实现Runnable

String类是final的,它不实现Runnable接口。因此,r instanceof String永远不能返回 true(因为不可能有任何String子类可以实现Runnable(,这就是编译器不允许它的原因。

另一方面,可能存在实现Runnable接口的Vector类或FileNotFoundException类的子类,因此r instanceof Vectorr instanceof FileNotFoundException可能会返回 true。

JLS 15.20.2 涵盖了这一点:

如果将关系表达式强制转换 (§15.16( 到 ReferenceType 将作为编译时错误而被拒绝,则关系表达式实例同样会产生编译时错误。在这种情况下,表达式实例的结果永远不可能是真的