Wednesday, July 23, 2008

Dynamic binding

Dynamic binding
What’s amazing about the code in doStuff( ) is that somehow the right thing happens.
Calling draw( ) for Circle causes different code to be executed than when calling draw( ) for
a Square or a Line, but when the draw( ) message is sent to an anonymous Shape, the
correct behavior occurs based on the actual type that the Shape handle happens to be
connected to. This is amazing because when the Java compiler is compiling the code for
doStuff( ), it cannot know exactly what types it is dealing with. So ordinarily, you’d expect
it to end up calling the version of erase( ) for Shape, and draw( ) for Shape and not for the
specific Circle, Square, or Line. And yet the right thing happens. Here’s how it works.
When you send a message to an object even though you don’t know what specific type it is,
and the right thing happens, that’s called polymorphism. The process used by object-oriented
programming languages to implement polymorphism is called dynamic binding. The
compiler and run-time system handle the details; all you need to know is that it happens
and more importantly how to design with it.
Some languages require you to use a special keyword to enable dynamic binding. In C++
this keyword is virtual. In Java, you never need to remember to add a keyword because
functions are automatically dynamically bound. So you can always expect that when you
send a message to an object, the object will do the right thing, even when upcasting is
involved.
50 Thinking in Java www.BruceEckel.com

0 comments: