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?
You're reading it the wrong way. instanceof
always evaluates to false
for null
references.
From the Java specification (emphasis mine):
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With