We have 2 overloaded methods, one has Integer and another has String as parameter. You are calling method with null. Which method will be called
Question:
You have 2 overloaded methods, doSomething, in below code. One takes Integer as parameter whereas another takes String. If you call it with null, which method will be called? What should be output of below code?public class OverloadDemo { public void doSomething(String str){ System.out.println("do something with String"); } public void doSomething(Integer str){ System.out.println("do something with Integer"); } public static void main(String[] args) { OverloadDemo overloadDemo = new OverloadDemo(); overloadDemo.doSomething(null); } }
Answer:
Compilation error - The method doSomething(String) is ambiguous for the type OverloadDemo
We can have solution for this problem is as follows:
ReplyDeleteSolution1 : If we want to call method with Integer argument:
public class OverloadDemo {
public void doSomething(String str){
System.out.println("do something with String");
}
public void doSomething(Integer str){
System.out.println("do something with Integer");
}
public static void main(String[] args) {
OverloadDemo overloadDemo = new OverloadDemo();
Integer a = null;
overloadDemo.doSomething(a);
}
}
OR
Solution2 : If we want to call method with String argument:
public class OverloadDemo {
public void doSomething(String str){
System.out.println("do something with String");
}
public void doSomething(Integer str){
System.out.println("do something with Integer");
}
public static void main(String[] args) {
OverloadDemo overloadDemo = new OverloadDemo();
String a = null;
overloadDemo.doSomething(a);
}
}