This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Why the below program gives o/p as String version & not Object version If I change Object to Integer or StringBuffer it gives compiler error reference to method is ambiguous.I can't understand why it is so ? public class Test { public void method(Object o) { System.out.println("Object version"); } public void method(String s) { System.out.println("String version"); } public static void main(String args[]) { Test test=new Test(); test.method(null); } }
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
The real question is how does Java handle null? The method overloading is working just fine. If you change the Object method to Integer you will get the ambiguous error. I do not know the reason the method is being used with the null but if you want to see the method overloading work initilized some objects of the same types as your method then make them null.
------------------
Rob Acraman
Ranch Hand
Joined: Dec 03, 2000
Posts: 89
posted
0
When deciding which overloaded method to call, the JVM will always try to pick the mathod with the most specific matching argument. In your case as given, both String and Object match the call, so since String is a subtype (ie. more specific) of Object, then it's called. When you change method(Object) to method(Integer), then both method(Integer) and method(String) match the call. However, since String and Integer aren't related, there's no clue for the JVM to decide which to call - hence the Ambiguous message.
asheesh talwar
Ranch Hand
Joined: Dec 10, 2000
Posts: 31
posted
0
Thanx Rob
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.