User Guide

Example: GeometricShapes 155
The describe() method also uses the super() statement, but in a different way—to invoke
the RegularPolygon superclass’ version of the
describe() method. The
EquilateralTriangle.describe() method first sets the desc string variable to a statement
about the type of shape. Then it gets the results of the
RegularPolygon.describe() method
by calling
super.describe(), and it appends that result to the desc string.
The Square class wont be described in detail here, but it is similar to the EquilateralTriangle
class, providing a constructor and its own implementations of the
getArea() and
describe() methods.
Polymorphism and the factory method
A set of classes that make good use of interfaces and inheritance can be used in many
interesting ways. For example, all of the shape classes described so far either implement the
IGeometricShape interface or extend a superclass that does. So if you define a variable to be an
instance of IGeometricShape, you dont have to know whether it is actually an instance of the
Circle or the Square class in order to call its
describe() method.
The following code shows how this works:
var myShape:IGeometricShape = new Circle(100);
trace(myShape.describe());
When myShape.describe() is called, it executes the method Circle.describe() because
even though the variable is defined as an instance of the IGeometricShape interface, Circle is
its underlying class.
This example shows the principle of polymorphism in action: the exact same method call
results in different code being executed, depending on the class of the object whose method is
being invoked.
The GeometricShapes application applies this kind of interface-based polymorphism using a
simplified version of a design pattern known as the factory method. The term factory method
refers to a function that returns an object whose underlying data type or contents can differ
depending on the context.
The GeometricShapeFactory class shown here defines a factory method named
createShape():
package com.example.programmingas3.geometricshapes
{
public class GeometricShapeFactory
{
public static var currentShape:IGeometricShape;
public static function createShape(shapeName:String,
len:Number):IGeometricShape