Damien Cassou, Stéphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr
Goal
What is overloading?
Why is it a problem?
What can you do?
This lecture is in the context of the Java programming language.
It is an incentive to understand for real double dispatch (without overloading)
Overloading
Overloading: methods sharing a name.
Seems nice at first to avoid thinking about names.
Exercise
What are the results of these 4 expressions?
Solution
B.f(A)
B.f(A)
B.f(A)
B.f(B)
Explanation
Overloading + sub-typing is confusing in Java.
In the presence of a message send, the compiler searches a compatible signature and stores it. During execution, the lookup algorithm searches for a method with this exact signature, regardless of the dynamic types of arguments.
Looking at a Real Case: a Visitor
All is well in this perfect world...
Uh! My Visitor is not Executed!
When method SubA.accept() is compiled, the message visitor.visit(this) is bound to visit(A), the only compatible signature in Visitor. During execution, visit(SubA) is ignored.
Possible Ugly 'Solutions'
One way to fix that could be to add a visit(SubA) method in Visitor (if you can change it):
This works but has 2 problems (see next slides):
the methods accept() in A and SubA are identical
you can't use the visit() methods directly
In Particular
The methods accept() in A and SubA are identical:
You could think that SubA.accept() is useless because its content is the same as A.accept(). But it's not useless as, inside it, the message visitor.visit(this) binds to the signature visit(SubA) which is what we want.
In Particular
You can't use the visit() methods directly:
If you use the visitor directly (i.e., without going through accept() methods), the static types become important to decide which visit() method to execute.
The Real Solution
Don't use overloading and prefer dedicated method names:
Summary
overloading is nice
just pay attention you don't mix it with sub-typing...