13.5 Polymorphism


13.5 Polymorphism

An object reference of a super type can refer to objects of different subtypes. This is possible from the subtyping principle explained before. To illustrate this concept, the following code creates objects for the object references triangle_obj, circle_obj, and rect_obj. Assume there is a declaration for variables x, y, z, and r.

       create triangle_obj of class Triangle using x, y, z       create circle_obj of class Circle using r       create rect_obj of class Rectangle using x, y 

The object reference gen_figure of class Gfigures can be assigned to refer to any of the three objects, triangle_obj, circle_obj, and rect_obj, created previously. For example, the following link implements such an assignment.

       set gen_figure = triangle_obj 

This is perfectly legal, because the type of object reference triangle_obj is a subtype of the type of object gen_figure. After this assignment, it is possible to invoke a function of the abstract class Gfigures that is implemented in the subclass Triangle. For example, the following code invokes function perimeter:

       call perimeter of gen_figure 

The actual function invoked is the one implemented in class Triangle, because it is the type of object reference triangle_obj. At some other point in the program (possibly in function main), another similar assignment could be included. The following code assigns the object reference circle_obj to the object reference gen_figure.

       set gen_figure = circle_obj 

The call to function perimeter is the same as before, because the three subtypes represented by the three subclasses Rectangle, Circle, and Triangle implement function perimeter. Because the implementation for this function is different in the three classes, the runtime system of the Java compiler selects the right version of the function.

Polymorphism is a runtime mechanism of the language that allows the selection of the right version of a function to be executed depending on the actual type of the object. Only one among several possible functions is really called. This function selection is based on late binding because it occurs at execution time.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net