I have a class which treats Strings as a collection. These are two methods from the class:
@Override
public <B> IndexedSeq<B> map(final Function1<? super Character, B> function) {...}
public RichString map(final Function1<? super Character, Character> function) {...}
Just the signature from the methods are relevant to my question. Now, Eclipse does issue a warning that the two methods have the same erasure. But it still allows me to create them, and they work as expected: Whenever I supply a function which transforms Character to Character, a RichString is returned, as I wanted.
My question is why does it work, since in runtime there's no information about the generic types, and the return of the method is not part of the method signature? How can the JVM knows which of the two methods to call, when I call them?
Edit:
I think, after the erasure, the two methods would have the following signature:
@Override
public IndexedSeq map(final Function1<Object, Object> function) {...}
public RichString map(final Function1<Object, Object> function) {...}
Which would make them differ only by the return type.
Two Methods cannot have same method signature. Methods can have same method name, and this process called method overloading.
Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
The signature of a method consists of the name of the method and the description (i.e., type, number, and position) of its parameters. Example: toUpperCase()
You're correct that this shouldn't compile. There's a bug in Java 6 that caused code like this to be incorrectly accepted: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6182950
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