views:

206

answers:

5

In situations where two interfaces apply to an object, and there are two overloaded methods that differ only by distinguishing between those interfaces, which method gets called?

In code.

interface Foo {}
interface Bar {}

class Jaz implements Foo, Bar {}

void DoSomething(Foo theObject)
{
    System.out.println("Foo");
}

void DoSomething(Bar theObject)
{
    System.out.println("Bar");
}

Jaz j = new Jaz();
DoSomething(j);

Which method will get called? DoSomething(Foo) or DoSomething(Bar)? Neither is more specific than the other, and I see no reason why one should be called instead of the other, except that one is specified first/last.

EDIT: And with this type of code is it possible to force one or the other method?

+12  A: 

This should be a compiler error.

This works:

DoSomething((Foo)j);
DoSomething((Bar)j);
Clint
+9  A: 

I'm pretty sure the above won't compile. DoSomething(j) is an ambiguous call and will result in an error.

To get it to compile, you'd have to specifically cast j as a Foo or Bar when you call DoSomething, for example DoSomething((Foo)j).

lc
A: 

That's an ambiguity in languages without renaming, most languages. Your best bet is to build two classes that implement the interface separately and make calls on the master object depending on which implementation you need to execute.

If you want to see a language that has function renaming check out Eiffel. http://dev.eiffel.com

+1  A: 

Is not ambiguos.

The signature of the method is: NAME and PARAMETERS

those methods are different.

void DoSomething(Foo theObject); //SIGNATURE IS: DoSomething,Foo

void DoSomething(Bar theObject); //SIGNATURE IS: DoSomething,Bar

tommaso
the methods themselves are *not* ambiguos, you are right. However, the method call `DoSomething(j)` is, since j is both a Foo and a Bar.
Mike Cooper
A: 

If the compiler is in doubt, it requires the programmer to cast the argument so it is not ambigous anymore.

Try passing "null" as a parameter.

Thorbjørn Ravn Andersen