- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Method Overloading and Ambiguity in Varargs in Java
There are ambiguities while using variable arguments in Java. This happens because two methods can definitely be valid enough to be called by data values. Due to this, the compiler doesn’t have the knowledge as to which method to call.
Example
public class Demo { static void my_fun(double ... my_Val){ System.out.print("fun(double ...): " + "Number of args: " + my_Val.length ); for(double x : my_Val) System.out.print(x + " "); System.out.println(); } static void my_fun(boolean ... my_Val){ System.out.print("fun(boolean ...) " + "The number of arguments: " + my_Val.length); for(boolean x : my_Val) System.out.print(x + " "); System.out.println(); } public static void main(String args[]){ my_fun(11.56, 34.78, 99.09, 56.66); System.out.println("Function 1 has been successfully called"); my_fun(true, false, true, false); System.out.println("Function 2 has been successfully called"); my_fun(); System.out.println("Function 3 has been successfully called"); } }
Output
Demo.java:23: error: reference to my_fun is ambiguous my_fun(); ^ both method my_fun(double...) in Demo and method my_fun(boolean...) in Demo match 1 error
A class named Demo defines a function named ‘my_fun’ that takes variable number of floating point values. The values are printed on the console using a ‘for’ loop. This function is overloaded and the parameters are boolean values that are varying in number. The output is displayed on the console using ‘for’ loop.
In the main function, the ‘my_fun’ is first called with floating ppoint values and then with Boolean values and then without any parameters. The exception that it results in, is displayed on the console.
- Related Articles
- Overloading Varargs Methods in Java
- Overloaded method and ambiguity in C#
- Method overloading in Java
- Method Overloading and null error in Java
- method overloading and type promotion in Java
- Difference between Method Overloading and Method Overriding in Java
- Using Method Overloading in Java
- Method overloading with autoboxing and widening in Java.
- What is method overloading in Java?
- What is the difference between method overloading and method hiding in Java?
- Explain about Varargs in java?
- Using Varargs with standard arguments in Java
- What are the restrictions placed on method overloading in java?
- Overloading in java programming
- Constructor overloading in Java
