gpt4 book ai didi

java - 空引用是一个类的实例吗?

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:26 24 4
gpt4 key购买 nike

这是一个简单的代码

class Foo {
}

class Bar extends Foo {
}

public class Main {

public static void main(String[] args) throws Exception {
fn(null);
}

static void fn(Foo f) {
System.out.println(f instanceof Foo ? "Foo" : "Bar");
}
}

我的问题是:Java 如何知道传递的 null 是 Bar 而不是 Foo?我知道为什么编译器选择 Bar 而不是 Foo(因为存在从 foo 到 bar 和从 bar 到 foo 的转换,反之亦然)。但是该方法如何知道这个 null 来自 Bar 而不是 Foo?null 是否包含有关分配给的对象的一些信息?

最佳答案

你读错了。对于 null 引用,instanceof 总是 的计算结果为 false

来自Java specification (强调我的):

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.

关于java - 空引用是一个类的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8933542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com