According to page 192 in the book Certified Associate Java SE 8 Programmer I by Jeanne Boyarsky and Scott Selikoff, "With overloading, you just write code and Java calls the right method."
However, the claim that Java automatically calls the correct method seems false according to the errors in my code:
The error on line 10 says, "Type mismatch: cannot convert from void to int", even though two of the other methods in the class have an int return type. Out of all the available methods, why would it automatically select the one with the void return type?
Also, when I comment out lines 23 - 26, the error on line 10 changes to, "The method fly(int, short) in the type Overloading is not applicable for the arguments (int)". What does that mean?
Lines 13 and 16: "Type mismatch: cannot convert from int to short".
Line 19: "Type mismatch: cannot convert from int to byte".
If this code example was in the real world, would casting data types like I did on line 14 be good practice?
You are calling the method with int as its parameter, and the compiler has correctly identified that. That method doesn't return anything, having void instead of its return type. But you are trying to assign the non‑return‑type to an int variable. You can't do that, as the compiler has noticed.
Then you have two other overloadings both correctly identified, both returning ints, but you cannot assign an int to a byte or a short variable without a cast. I think, in the real world, it probably would be bad practice to use shorts and bytes at all. There is however a good use for a byte: it can be sent across a network.
The Java compiler does not use the type of the return value to determine what method to apply.
So, as far as it is concerned, the following two methods would be classed as the same:
as your code shows, in fact.
Consequently, when you make a call to fly(<some int value>) the fact you are assigning the result to an int plays no part in the compiler deciding which method to apply. It picks solely based on the method name and the given parameters.
So your code does show it picking the correct method within the rules of the compiler, it's just that the code itself is incorrect.
Do you want ants? Because that's how you get ants. And a tiny ads:
Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps