5

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?

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77

5 Answers5

23

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
1

Is a null reference an instance of a class?

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.

My question is: How Java knows that the passed null is Bar and not Foo?

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.

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).

The compiler didn't mkae any such choice. Your code did a poorly designed test and print.

But how would the method know this null comes from Bar and not Foo?

It doesn't. It guessed. It got it wrong.

does null contain some information about the object which is assigned to?

It contains no information at all.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

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.

Gangnus
  • 24,044
  • 16
  • 90
  • 149
1

What do you mean by

How java knows that this null is Bar and not Foo?

null is neither Bar nor Foo. See Java method dispatch with null argument

Community
  • 1
  • 1
Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
0

null is a special type and that special type is "NullType".

G.S.Tomar
  • 290
  • 2
  • 14