为什么这个instanceof代码可以工作并且不会导致编译时错误?
在下面的代码中,x 的类型是 I(虽然 x 也实现了 J,但在编译时未知),那么为什么 (1) 处的代码不会导致编译时错误。 因为在编译时只考虑引用的类型。
public class MyClass {
public static void main(String[] args) {
I x = new D();
if (x instanceof J) //(1)
System.out.println("J");
}
}
interface I {}
interface J {}
class C implements I {}
class D extends C implements J {}
In the following code, the type of x is I (although x also implements J but thats not known at compile time) so why is it that the code at (1) doesn't result in a compile time error.
Because at compile time only the type of the reference is considered.
public class MyClass {
public static void main(String[] args) {
I x = new D();
if (x instanceof J) //(1)
System.out.println("J");
}
}
interface I {}
interface J {}
class C implements I {}
class D extends C implements J {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
instanceof
用于运行时确定对象类型。您试图在程序运行时确定 x 是否确实是 J 类型的对象,以便编译。您是否认为它应该导致编译时错误,因为您认为编译器不知道
x
的类型?编辑
正如 Kirk Woll 评论的那样(感谢 Kirk Woll!),如果您检查
x
是否是具体类的instance
,并且编译器可以确定x
的类型,那么你会在编译时得到一个错误。来自 Java 语言规范:
举个例子:
instanceof
is used used for runtime determination of an object's type. You are trying to determine ifx
is really an object of typeJ
when the program is running, so it compiles.Were you thinking it should result in a compile-time error because you think the compiler does not know
x
's type?Edit
As Kirk Woll has commented (thanks Kirk Woll!), if you were checking if
x
is aninstanceof
a concrete class, and the compiler can determinex
's type, then you will get an error at compile time.From the Java Language Specification:
As an example of this:
instanceof 是一个运行时运算符,而不是编译时运算符,因此它是使用所引用对象的实际类型进行评估的。
instanceof is a run-time operator, not compile-time, so it's being evaluated using the actual type of the object being referenced.