User Guide
154 Object-Oriented Programming in ActionScript
The following code for the EquilateralTriangle class show how the getArea() method is
overridden:
package com.example.programmingas3.geometricshapes
{
public class EquilateralTriangle extends RegularPolygon
{
public function EquilateralTriangle(len:Number = 100):void
{
super(len, 3);
}
public override function getArea():Number
{
// The formula is ((sideLength squared) * (square root of 3)) / 4.
return ( (this.sideLength * this.sideLength) * Math.sqrt(3) ) / 4;
}
public override function describe():String
{
/* starts with the name of the shape, then delegates the rest
of the description work to the RegularPolygon superclass */
var desc:String = "This shape is an equilateral Triangle.\n";
desc += super.describe();
return desc;
}
}
}
The override keyword indicates that the EquilateralTriangle.getArea() method
intentionally overrides the
getArea() method from the RegularPolygon superclass. When the
EquilateralTriangle.getArea() method is called, it calculates the area using the formula
in the preceding code, and the code in the
RegularPolygon.getArea() method never
executes.
In contrast, the EquilateralTriangle class doesn’t define its own version of the
getPerimeter() method. When the EquilateralTriangle.getPerimeter() method is
called, the call goes up the inheritance chain and executes the code in the
getPerimeter()
method of the RegularPolygon superclass.
The
EquilateralTriangle() contructor uses the super() statement to explicitly invoke the
RegularPolygon() contructor of its superclass. If both constructors had the same set of
parameters, you could have omitted the EquilateralTriangle constructor completely, and the
RegularPolygon() contructor would be executed instead. However, the RegularPolygon()
contructor needs an extra parameter,
numSides. So the EquilateralTriangle() constructor
calls
super(len, 3) which passes along the len input parameter and the value 3 to indicate
that the triangle will have 3 sides.