O'Reilly logo

Prefactoring by Ken Pugh

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.4. Polymorphism

Polymorphism deals with manipulating objects of different classes using only the interface that they have in common. There are two different uses for polymorphism . In the first case, there are different implementations of an interface with the same behavior, such as with printer drivers. In the second case, there are different behaviors with the same interface, such as proxy classes with different operations.

You can code classes to be polymorphic in two ways.[*] One way is to use inheritance. Derived classes share the interface of the base class. The second way is to implement interfaces in languages such as Java and C#.

[*] A reviewer noted that in Ruby, there is a third way called Duck Typing, whereby any class with a matching method name can handle a method. It does not have to implement an interface or extend a base class.

6.4.1. Using Inheritance

A typical example of an inheritance hierarchy has a Shape base class. Shapes such as Rectangle and Triangle are derived from Shape, as shown in Figure 6-1. A Square shape is then derived from Rectangle, and an EquilateralTriangle is derived from Triangle.

An EquilateralTriangle and a Square have a facet in common that is not represented in this inheritance hierarchy. They both represent regular polygons (all their sides are the same length).

6.4.2. Using Interfaces

Instead of using inheritance, you could code the relationship with interfaces, as shown in Figure 6-2.

When Squares and EquilateralTriangle

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required