In Java, it's quite common to overload methods. Below is a stimulating Java program.
public class Test { // Overloaded methods public void fun(Integer i) { System.out.println("fun(Integer ) "); } public void fun(String name) { System.out.println("fun(String ) "); } // Driver code public static void main(String [] args) { Test mv = new Test(); // This line causes error mv.fun(null); } }
Output :
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 a compile-time error within the above scenario is, here the tactic arguments Integer and String both aren't primitive data types in Java. meaning they accept null values. once we pass a null value to method1 the compiler gets confused about which method it's top pick, as both are accepting the null.
This compile-time error wouldn’t happen unless we intentionally pass the null value. for instance, see the below scenario which we follow generally while coding.
public class Test { // Overloaded methods public void fun(Integer i) { System.out.println("fun(Integer ) "); } public void fun(String name) { System.out.println("fun(String ) "); } // Driver code public static void main(String [] args) { Test mv = new Test(); Integer arg = null; // No compiler error mv.fun(arg); } }
Output :
fun(Integer )
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.