From Dan Chisholm Casting questions:
class A {}
class B {
static void m(Object x) {System.out.print("Object");}
static void m(
String x) {System.out.print("String");}
public static void main(String[] args) {
m(null);
}
}
What is the result of attempting to compile and run the above program?
a. Prints: Object
b. Prints: String
c. Compiler error.
d. Runtime error.
e. None of the Above
ANSWER= B
Explanation:
Section 15.12.2.2 of the
Java Language Specification states the following. If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen. The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error. End of quote. In this case, the String type is more specific than the Object type.
-------------------
How can you send a 'null' into a method expecting a String? I know that when a method returns String a compile error results from return null;
Also, if you did:
RunTimeError rt = null;
throw rt; // NullPointerException
//must throw Throwable object, null is not a Throwable
Also, it is odd that null == Object returns true.
From my experience, I have concluded the following:
(1) you can send 'null' as a method parameter
(2) you cannot return 'null' from a method
Any insight on if I am right/wrong will be greatly appreciated.
Thank you.