Overloading methods and passing ‘null’ as argument
Posted by Martin Homik | Posted in Java | Posted on 28-10-2008
2
Today, I came across a NPE which pointed me to a problem which I cannot resolve. Assuming, you have two overloaded methods in a class:
Which method will be invoked when the parameter is null?
Answer: you cannot call setProperty with a null parameter. The compiler will complain. In all other cases the signature of the method is matched. So, it doesn’t matter if your String has the null value, it only matters that you apply a method applied to a String parameter. This is the signature. This is matched.


the good news is, that you can cast:
setProperty((String)null);
what if i pass Object as argument?
setProperty((Object)null);
or if the value null gets resolved at runtime?
e.g.
Object a = null;
setProperty(a );
how will javac or JRE react to such behavior?
- ankit