Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Method Resolution

Consider the following sequence of instructions:

GraphicalObject g1 = new Circle(new Point (0,0), 5);
GraphicalObject g2 = new Square(new Point (0,0), 5);
g1.Draw();
g2.Draw();
The statement g1.Draw() calls Circle.Draw whereas the statement g2.Draw() calls Rectangle.Draw.

It is as if every object of a class ``knows'' the actual method to be invoked when a method is called on that object. E.g, a Circle ``knows'' to call Circle.Draw, GraphicalObject.Erase and GraphicalObject.MoveTo, whereas a Square ``knows'' to call Rectangle.Draw, GraphicalObject.Erase and GraphicalObject.MoveTo.

In this way, C# ensures that the ``correct'' method is actually called, regardless of how the object is accessed. Consider the following sequence:

Square s = new Square(new Point(0,0), 5);
Rectangle r = s;
GraphicalObject g = r;
Here s, r and g all refer to the same object, even though they are all of different types. However, because the object is a Square, s.Draw(), r.Draw() and g.Draw() all invoke Rectangle.Draw.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.