Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a null reference an instance of a class?

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?

like image 903
Sleiman Jneidi Avatar asked Jan 19 '12 21:01

Sleiman Jneidi


2 Answers

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.

like image 152
Etienne de Martel Avatar answered Sep 29 '22 19:09

Etienne de Martel


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.

like image 42
Gangnus Avatar answered Sep 29 '22 17:09

Gangnus