Method Overloading

Postmortem of Method Overloading in Java.

Hello Code geeks,
I’m back again to share with you all an interesting overloading concept which I have just learnt.

Java Overlaoding

Overloading


Please have a look at the following code,


public class OverloadDemo {

	
	public static void  hello(Integer i)
	{
		System.out.println("Integer");
	}
	
	public static void  hello(String s)
	{
		System.out.println("String");
	}
	
	public static void main(String[] args) {
		
		hello(null);
        hello(1);
        hello("one");
	}

}

What will be the output of the program?
How many of you have noticed that there is a compilation error in the above code. Well, yes there is a compilation error at Line 16 which says “The method hello(Integer) is ambiguous for the type OverloadDemo”

I was playing around with some programs implementing method overloading. I got this error. So, let’s jump in right away and figure out what’s the root cause.

So, here we have method hello which is overloaded with two different parameters.
1.hello(Integer i)
2.hello(String s)
So, Here if we pass a value like hello(1), the Integer version of it will be called and output will be Integer and if we call like this hello(“One”), the String version of it will be called and output will be String.

So, why are we getting a compilation error once we try to pass hello(null). Because, as String and Integer are classes and they both can have null values.When compiler executes it, it will be ambiguous for it, as which method it has to call. Is it hello(Integer)? Which can also take a null argument or Is it hello(String) which as well can take a null argument again.

So, for solving this, changes the Integer to int.Then everything works fine.Now, as we identified the root cause for this issue, this can be fixed by whatever the way it is possible.

Forgot to mention that, I’m preparing for OCJP7 Up gradation exam.So, that’s the reason I’m coming across such things while I’m coding.This might look simple, but in the OCJP we might not actually get it right unless we’re aware or came across of such a scenario.As I always say, OCJP is all about tricky questions.

Have a Good Night.

Advertisements