User Guide

130 Object-Oriented Programming in ActionScript
Inheritance
Inheritance is a form of code reuse that allows programmers to develop new classes that are
based on existing classes. The existing classes are often referred to as base classes or superclasses,
while the new classes are usually called subclasses. A key advantage of inheritance is that it
allows you to reuse code from a base class yet leave the existing code unmodified. Moreover,
inheritance requires no changes to the way that other classes interact with the base class.
Rather than modifying an existing class that may have been thoroughly tested or may already
be in use, using inheritance you can treat that class as an integrated module that you can
extend with additional properties or methods. Accordingly, you use the
extends keyword to
indicate that a class inherits from another class.
Inheritance also allows you to take advantage of polymorphism in your code. Polymorphism is
the ability to use a single method name for a method that behaves differently when applied to
different data types. A simple example is a base class named Shape with two subclasses named
Circle and Square. The Shape class defines a method named
area(), which returns the area of
the shape. If polymorphism is implemented, you can call the
area() method on objects of
type Circle and Square and have the correct calculations done for you. Inheritance enables
polymorphism by allowing subclasses to inherit and redefine, or override, methods from the
base class. In the following example, the
area() method is redefined by the Circle and Square
classes:
class Shape
{
public function area():Number
{
return NaN;
}
}
class Circle extends Shape
{
private var radius:Number = 1;
override public function area():Number
{
return (Math.PI * (radius * radius));
}
}
class Square extends Shape
{
private var side:Number = 1;
override public function area():Number
{
return (side * side);
}