In Java it is very common to overload methods. Below is an interesting Java program.
22: error: reference to fun is ambiguous mv.fun(null); ^ both method fun(Integer) in Test and method fun(String) in Test match 1 error
The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null.
This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding.
In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that.
Note: This problem wouldn’t persist when the overriden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it.
This article is contributed by Nageswara Rao Maridu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Calling a method using null in Java
- Different ways of Method Overloading in Java
- Difference between Method Overloading and Method Overriding in Java
- Method Overloading with Autoboxing and Widening in Java
- Method Overloading and Ambiguity in Varargs in Java
- Null Pointer Exception In Java
- Interesting facts about null in Java
- Program to check if the String is Null in Java
- Replace null values with default value in Java Map
- Overloading in Java
- Constructor Overloading in Java
- GFact 48 | Overloading main() in Java
- Output of Java program | Set 22 (Overloading)
- Java Function/Constructor Overloading Puzzle
- Overloading of Thread class run() method
- Unreachable Code Error in Java
- Bit Stuffing error detection technique using Java
- Function overloading and return type
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
Improved By : imeenalgrover