TheFreeSite.com!

Monday, July 28, 2008

Interchangeable objects with polymorphism

Inheritance usually ends up creating a family of classes, all based on the same uniform
interface. We express this with an inverted tree diagram:5
One of the most important things you do with such a family of classes is to treat an object
of a derived class as an object of the base class. This is important because it means you can
write a single piece of code that ignores the specific details of type and talks just to the base
class. That code is then decoupled from type-specific information, and thus is simpler to
write and easier to understand. And, if a new type – a Triangle, for example – is added
through inheritance, the code you write will work just as well for the new type of Shape as
it did on the existing types. Thus the program is extensible.
Consider the above example. If you write a function in Java:
void doStuff(Shape s) {
s.erase();
// ...
s.draw();
}
This function speaks to any Shape, so it is independent of the specific type of object it’s
drawing and erasing. If in some other program we use the doStuff( ) function:
Circle c = new Circle();
Triangle t = new Triangle();
Line l = new Line();
doStuff(c);
doStuff(t);
doStuff(l);
5 This uses the Unified Notation, which will primarily be used in this book.
Shape
draw()
erase()
Circle
draw()
erase(
Square
draw()
erase()
Line
draw()
erase()
Chapter 1: Introduction to Objects 49
The calls to doStuff( ) automatically work right, regardless of the exact type of the object.
This is actually a pretty amazing trick. Consider the line:
doStuff(c);
What’s happening here is that a Circle handle is being passed into a function that’s
expecting a Shape handle. Since a Circle is a Shape it can be treated as one by doStuff( ).
That is, any message that doStuff( ) can send to a Shape, a Circle can accept. So it is a
completely safe and logical thing to do.
We call this process of treating a derived type as though it were its base type upcasting. The
name cast is used in the sense of casting into a mold and the up comes from the way the
inheritance diagram is typically arranged, with the base type at the top and the derived
classes fanning out downward. Thus, casting to a base type is moving up the inheritance
diagram: upcasting.
An object-oriented program contains some upcasting somewhere, because that’s how you
decouple yourself from knowing about the exact type you’re working with. Look at the code
in doStuff( ):
s.erase();
// ...
s.draw();
Notice that it doesn’t say “If you’re a Circle, do this, if you’re a Square, do that, etc.” If you
write that kind of code, which checks for all the possible types a Shape can actually be, it’s
messy and you need to change it every time you add a new kind of Shape. Here, you just
say “You’re a shape, I know you can erase( ) yourself, do it and take care of the details
correctly.”

0 comments:

Tell Me Doubts In Java