为什么这个instanceof代码工作并且不会导致编译时错误? [英] Why does this instanceof code work and does not cause a compile time error?

查看:107
本文介绍了为什么这个instanceof代码工作并且不会导致编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,x的类型是I(虽然x也实现了J但在编译时不知道),为什么(1)处的代码不会导致编译时错误。
因为在编译时只考虑引用的类型。

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 {}


推荐答案

instanceof 用于运行时确定对象的类型。您正在尝试确定 x 在程序运行时是否真的是 J 类型的对象,因此它会进行编译。

instanceof is used used for runtime determination of an object's type. You are trying to determine if x is really an object of type J when the program is running, so it compiles.

您是否认为它会导致编译时错误,因为您认为编译器不知道 x ' s类型?

Were you thinking it should result in a compile-time error because you think the compiler does not know x's type?

编辑

正如Kirk Woll评论的那样(感谢Kirk Woll !),如果你检查 x instanceof 具体类,编译器可以确定 x 的类型,然后在编译时会出错。

As Kirk Woll has commented (thanks Kirk Woll!), if you were checking if x is an instanceof a concrete class, and the compiler can determine x's type, then you will get an error at compile time.

来自Java语言规范:

From the Java Language Specification:


如果将RelationalExpression转换为ReferenceType将作为编译时错误被拒绝,则关系表达式的实例同样会产生编译时错误。在这种情况下,instanceof表达式的结果永远不会成立。

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

作为一个例子:

import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

class SerializableClass implements Serializable
{
   private writeObject(ObjectOutputStream out) {}
   private readObject(ObjectInputStream in) {}
}

public class DerivedSerializableClass extends SerializableClass
{
   public static void main(String[] args)
   {
      DerivedSerializableClass dsc = new DerivedSerializableClass();

      if (dsc instanceof DerivedSerializableClass) {} // fine
      if (dsc instanceof Serializable) {} // fine because check is done at runtime
      if (dsc instanceof String) {} // error because compiler knows dsc has no derivation from String in the hierarchy

      Object o = (Object)dsc;
      if (o instanceof DerivedSerializableClass) {} // fine because you made it Object, so runtime determination is necessary
   }
}

这篇关于为什么这个instanceof代码工作并且不会导致编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆