简体   繁体   中英

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??

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM