Calls to overloaded methods are resolved at compile time, depending on the type of the argument. Calls to overridden methods are resolved at runtime, depending on the type of the actual object denoted by the argument.
(From Khalid Mughal, Chapter 11). What is this depending on the argument. In that case if the argument is different will a overloaded method will be resolved at run time. Anybody can clear this with an example if possible?
Hi Marc, The whole text and its context is as below:
The compiler will not complain. Calls to overloaded methods are resolved at compile time, depending on the type of the argument. Calls to overridden methods are resolved at runtime, depending on the type of the actual object denoted by the argument. Comparing the objects of the class MyRefType that overloads the equals() method for equivalence, can give inconsistent results:
Its because equals() method is overloaded in MyRefType. So when you call the equals() method as above. The method that should be called will be based on reference type and since ref3 is of Object type the equals() method of Object class will be called.
Hi Overloaded method is chosen in the following way: 1. Compiler checks for the exact type of arguments to parameters 2. If it doesnt find, then it widens the arguments like int to long, or YourClass object to Object class object. 3. If widening is also not possible, it looks for Boxing/unboxing 4. If the above 3 fails, it looks for var-args list
In your case, the equals method is not overridden but overloaded. That means more than one methods with same name are present. So when you call with the reference of the Object object argument, (the above first principle) exact match is found and Object's equals returns FALSE.
Hi uday, I've a doubt in boxing and widening.. In K&B book, its given that, "You CANNOT Widen and then Box(An int can't become a Long)" in page no. 244. My view is , generally, you can widen an int to long or double, then you can use the wrapper utility to convert the same to Long or Double object. If this is possible then, why not Widen and then Box. If my understanding is wrong, please clear this point to me.
Note: Wrapper classes don't have any relationships with each other. For example all the numeric wrappers just extend from the java.lang.Number class; They are child of one parent. Because there is not parent child relationship between one wrapper with another one. That is why Widen and Box is wrong to do. int can't become Long via long but int c an become Object via Integer >> Number.
machines help you to do more, but experience less. Experience this tiny ad: