Duplicate Method while Method-Overloading
Solution 1
Resolving overloaded methods is done at compile-time, rather than runtime, so the Java compiler would know the difference between the two in your second example. In your third example, the problem is that a List<Integer>
is also a List
, so it wouldn't know which one to use if you passed in a List<Integer>
.
Solution 2
- Java can not determine which one to use if the parameters are the same. So, it throws a duplicate method error instead.
List
ofString
andList
ofInteger
are not directly conversible, so the methods are different. No error.List
ofInteger
can also be used as a plainList
of anything, so Java can't determine which one to use if supplied aList
ofInteger
-> duplicate method error.
Kumar
Updated on June 04, 2022Comments
-
Kumar almost 2 years
Following code gives compilation error with error "Duplicate Method"
static int test(int i){ return 1; } static String test(int i){ return "abc"; }
This is expected as both the overloaded method have same signature and differ only in return type.
But the following code compiles fine with a warning:
static int test1(List<Integer> l){ return 1; } static String test1(List<String> l){ return "abc"; }
As, we know the Java Generics works on Erasure, which mean in byte-code, both these method have exactly the same signature and differs with return type.
Furthur, to my surprise the following code again gives compilation error:
static int test1(List<Integer> l){ return 1; } static String test1(List l){ return "abc"; }
How is the second code working fine without giving any compilation error, though there is duplicate method?