npocmaka
npocmaka

Reputation: 57252

Why I can pass null as argument to method without null being instance of accepted parameters?

public static String instanceTest(Comparable cmp) {
    if (cmp == null) {
        return "null";
    }
    else return cmp.toString();
} 
public static void main(String[] args) {
    Comparable comp = null;
    //comp = new FileReader(""); cannot be converted
    System.out.println(null instanceof Comparable);
    System.out.println(comp instanceof Comparable);
    System.out.println(instanceTest(null));
}

This example confuses me. The instanceTest method accepts only Comparable.null is not an object and cannot be instance of Comparable.But passing null to instanceTest is compiled and even can be executed.Why? Even more confusing - I can create a Comparable object comp that points to null. The instanceof fails with the comp instanceof Comparable but I cannot convert the object to another type that is not Comparable.Obviously instanceof checks the object but not the reference? But the reference also contains some information about it's type ? So is there a way to check the type of the reference??

Upvotes: 3

Views: 178

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

The Java Language Specification states

The null reference can always undergo a widening reference conversion to any reference type.

where widening reference conversion is defined as

A widening reference conversion exists from any reference type S to any reference type T, provided S is a subtype (§4.10) of T.

So although null isn't an instance of type Comparable (it's not an instance at all, it's a reference), it can be used in the place of a reference of type Comparable (or any other reference type).

So is there a way to check the type of the reference??

You are already doing it with == and instanceof.

Upvotes: 4

Related Questions