Reputation: 83
I have a misunderstanding with overloaded methods in Java.
Are these overloaded or not?
public String eJava(int age, String name, double duration);
float eJava(double name, String age, byte duration);
In test that i wrote the answer is YES. But i don't think so. Reason: Let's take an example of method arguments: eJava(111, "word", 222);
Those arguments can be passed to both methods, as i know. Because 111 can be accepted by double and int, "word" is accepted by String and 222 can be accepted by byte or double. So i think that correct answer is "compilation error".
Ok, those methods have different return types, but that is not important.
What am i doing wrong? Thank You
Upvotes: 3
Views: 878
Reputation: 94
A class may have more than one method with the same name, but
with different argument lists. This is called method overloading.
For example:
method with the same names:
System.out.println("Hello")
-->with type String
System.out.println(4+8)
-->with type int
System.out.println("I have"+100+"$")
--> with type String + int
second example:
method with the same names:
int size(int height,int width)
--two type in parameter
int size(int distance)
-->one type in peremeter.
Upvotes: 0
Reputation: 11621
Yes they are overloaded methods, because they have the same name but different argument types. apomeme's answer gives more detail.
To answer the second question:
Your call eJava(111, "word", 222)
is not ambiguous, and not a compilation error. It matches the first method: eJava(int age, String name, double duration)
. It cannot match the second method, because its third argument is a byte, and an int literal cannot be implicitly converted to a byte. Such narrowing conversions are disallowed unless you explicitly cast them.
However, if the second method was
float eJava(double name, String age, long duration)
then the call would indeed be ambiguous and a compilation error, because an int literal can be implicitly converted to long.
Upvotes: 5
Reputation: 14389
Going by definition:
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. There are two ways to overload the method in java
By changing number of arguments By changing the data type
So the correct answer is YES, those are two overloaded methods
Upvotes: 5