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