Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
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, Java 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 © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.