I was expecting some kind of exception at runtime from the below code but to my surprise the code ran without any issues and the output was
"SubClass". From testing similiar code I understood that it chooses the method that takes argument which appears more lower in the inheritance tree. It should work fine if some super class/sub class reference was passed to it but how does it decide with null?
It might be pretty straightforward to some but I did not get it. Please help me understand this.
and yes, you are not doing any kind of operation on objects in method "printSomething" so exception will not come from any way.
Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Joined: Jul 10, 2009
Manish Singh wrote:
I was expecting some kind of exception at runtime
Overloading is completely decide by compiler so nothing remains for runtime.
You yourself explained that the compiler chooses exact or the most narrower match for a method call
Thanks for the explanations. After trying out samples I understood how it works.
But my doubt was something like this.
It is decided at compile time which method is to be called. And it decides on the base of the parameters to call the method having the most specific reference . So if I have a reference of the superclass then the method taking superclass as an argument is called. Thats fine. But with null how does it decide which is the method taking the most specific reference as an arg.
Another way I was putting it was for anymethod being called the arguments passed would pass the instanceof method check.
Does it mean that null is of the subclass type?
Please bear with me if you think my doubts are not worthwhile.