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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With