Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two methods with the same signature, why it works

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.

like image 385
Vinicius Seufitele Avatar asked May 07 '13 11:05

Vinicius Seufitele


People also ask

Can 2 methods have same signature?

Two Methods cannot have same method signature. Methods can have same method name, and this process called method overloading.

When methods have the same name and different signatures this is called?

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.

Is it possible to have two methods in a class with same method signature but different return types?

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.

What determines the signature of a method?

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()


1 Answers

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

like image 102
David Avatar answered Nov 14 '22 22:11

David