[Prev][Next][Index][Thread]
Re: Students/techniques
>>>>> "GG" == Gabor Greif <gabor@no.netopia.com> writes:
GG> Overloading in C++ works not only with (a hand-picked subset of) built-in
GG> operators, but also with user-defined functions in general.
GG> But this kind of overloading lacks the full power of generic functions,
GG> because method selection is done at compile time, based on the static
GG> (-ally inferrable) type of the arguments, not by the dynamic type of the
GG> objects. Virtual methods allow dynamic dispatch on the single and arbitrary
GG> receiver object.
This is also the big problem with overloading in Java. Overloading
gives the "feel" of dispatch by argument type, but it is misleading at
best.
As an example, consider the following example in Java:
// file A.java:
class A extends Object {
}
// file B.java:
class B extends A {
}
// file Problem1.java:
class Problem1 extends Object {
// A is a subclass of Object,
// B is a subclass of A.
public static String foo(A x) {
return bar(x);
}
public static String bar(A anA) {
return "bar on A";
}
public static String bar(B aB) {
return "bar on B";
}
public static void main (String[] args) {
B aB = new B();
String s = foo(aB);
System.out.println(s);
}
}
What should "javac *.java ; java Problem1" print?
It prints "bar on A", even though bar is called with a B object.
A "real" multimethod dispatch system would invoke the bar method on
B.
--
Greg gregs@ai.mit.edu (617)253-5807
Sullivan http://www.ai.mit.edu/~gregs/
References: