Hi:
I am out of school for a while, and often get confused with the method
dispatch mechanism in Java. I wish someone with a clear understanding of
dispatch mechainism can shed some light and tell me if the following
description is correct.
To my knowledge, there are two kinds of method dispatch: static and dynamic.
In Java, method overloading involves static method dispatch, and method
overriding involves dynamic dispatch. (Am I right here? someone told me that
Java does all method dispatch dynamically)
(1) The following is an example of static dispatch (method overloading)
class Confucius
{
void ride(Horse h)
{
System.out.println("Confucius rides a horse");
}
void ride(WhiteHorse h)
{
System.out.println("Confucius rides a white horse");
}
void ride(BlackHorse h)
{
System.out.println("Confucius rides a black horse");
}
}
and assuming that WhiteHorse and BlackHorse are subclasses of Horse class,
then the following would print out "Confucius rides a horse" statement three
times
Horse h = new Horse();
Horse wh = new WhiteHorse();
Horse bh = new BlackHorse();
Confucius c = new Confucius();
c.ride(h);
c.ride(bh);
c.ride(wh);
because the method overloading is resolved using static types, and this
decision is made at compile time. Therefore this should be a static
dispatch.
(2) The following example, which is nothing but a method overriding, is an
example of dynamic dispatch:
String s1 = "ab";
String s = "abc";
Object o = s1 + "c";
o.equals(s);
which would return true, because String is the actual type of o.
To make it clear, a dispatch made at compile time is called a static
dispatch. Because only apparent type is avaiable to compiler at compile
time, the static dispath decisions can only be according to apparent types.
On the other hand, a dispatch made at runtime according to dynamic and
actual types is dyanmic dispatch.
Thanks
Jeff
To change your membership options, refer to:
http://www.sys-con.com/java/list.cfm