Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Polymorphism?

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?

like image 455
Mike Cooper Avatar asked Nov 30 '22 06:11

Mike Cooper


2 Answers

This should be a compiler error.

This works:

DoSomething((Foo)j);
DoSomething((Bar)j);
like image 107
Clint Avatar answered Dec 05 '22 09:12

Clint


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

like image 38
lc. Avatar answered Dec 05 '22 10:12

lc.