空引用是类的实例吗?
这是一个简单的代码
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 是否包含有关分配给的对象的一些信息?
This is a simple code
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");
}
}
My question is: How Java knows that the passed null is Bar
and not Foo
?
I know why the compiler chooses Bar and not Foo (because there is a conversion from foo to bar and from bar to foo and not vice-versa).
But how would the method know this null comes from Bar and not Foo?
does null contain some information about the object which is assigned to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它总是假的。 Javac 知道。
但您可以使用 f.someStaticFunctionOfTheClassFoo()。所以,你的问题很有趣,只是需要编辑一下。
It is always false. Javac Knows it.
But you can use f.someStaticFunctionOfTheClassFoo(). So, your question is very interesting, only it needs to be edited.
你是什么意思
null
既不是Bar
也不是Foo
。请参阅带有 null 参数的 Java 方法调度What do you mean by
null
is neitherBar
norFoo
. See Java method dispatch with null argument让我们明确一下这一点。引用不是任何事物的实例。这是一个参考。它引用的对象(如果有的话)是某个类的实例。但空引用不引用任何对象。
事实并非如此。你的程序欺骗了你。如果引用不引用 Foo 的实例,它会打印“Bar”。您的编码不当。
编译器没有做出任何这样的选择。您的代码进行了设计不佳的测试和打印。
事实并非如此。它猜到了。它弄错了。
它根本不包含任何信息。
Let's be clear about this. A reference isn't an instance of anything. It is a reference. The object it refers to, if any, is an instance of some class. But the null reference doesn't refer to any object.
It doesn't. Your program lied to you. It prints "Bar" if the reference doesn't refer to an instance of Foo. Poor coding on your part.
The compiler didn't mkae any such choice. Your code did a poorly designed test and print.
It doesn't. It guessed. It got it wrong.
It contains no information at all.
null 是一种特殊类型,该特殊类型是“NullType”。
null is a special type and that special type is "NullType".
你读错了。对于
null
引用,instanceof
始终 计算结果为false
。来自 Java 规范(重点是我的):
You're reading it the wrong way.
instanceof
always evaluates tofalse
fornull
references.From the Java specification (emphasis mine):