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.
instanceofalways evaluates tofalsefornullreferences.From the Java specification (emphasis mine):