Reputation: 3048
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?
Upvotes: 4
Views: 748
Reputation: 75376
If the compiler is in doubt, it requires the programmer to cast the argument so it is not ambiguous anymore.
Try passing "null" as a parameter.
Upvotes: 0
Reputation: 9252
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
Upvotes: 0
Reputation: 116468
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)
.
Upvotes: 10
Reputation: 1429
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
Upvotes: 0
Reputation: 9058
This should be a compiler error.
This works:
DoSomething((Foo)j);
DoSomething((Bar)j);
Upvotes: 12