Interfaces in ActionScript

ActionScript doesn’t have a direct equivalent to interfaces as in other languages, but we can achieve similar functionality using classes and inheritance. Here’s how we can implement the concept of interfaces in ActionScript:

package {
    import flash.display.Sprite;
    import flash.geom.Point;

    public class Interfaces extends Sprite {
        public function Interfaces() {
            // Creating instances of our shapes
            var r:Rectangle = new Rectangle(3, 4);
            var c:Circle = new Circle(5);

            // Measuring our shapes
            measure(r);
            measure(c);
        }

        // This function takes any object that implements the IGeometry interface
        private function measure(g:IGeometry):void {
            trace(g);
            trace(g.area());
            trace(g.perim());
        }
    }
}

// This is our "interface" class
class IGeometry {
    public function area():Number { return 0; }
    public function perim():Number { return 0; }
}

class Rectangle extends IGeometry {
    private var width:Number;
    private var height:Number;

    public function Rectangle(w:Number, h:Number) {
        width = w;
        height = h;
    }

    override public function area():Number {
        return width * height;
    }

    override public function perim():Number {
        return 2 * width + 2 * height;
    }

    public function toString():String {
        return "{" + width + " " + height + "}";
    }
}

class Circle extends IGeometry {
    private var radius:Number;

    public function Circle(r:Number) {
        radius = r;
    }

    override public function area():Number {
        return Math.PI * radius * radius;
    }

    override public function perim():Number {
        return 2 * Math.PI * radius;
    }

    public function toString():String {
        return "{" + radius + "}";
    }
}

In this ActionScript code, we’ve created a base class IGeometry that serves as our “interface”. The Rectangle and Circle classes extend this base class and override its methods to provide their own implementations.

The measure function can accept any object that extends IGeometry, allowing us to use it with both Rectangle and Circle instances.

To run this code, you would typically embed it in a Flash project and compile it with the Adobe Flash Professional or Adobe Animate CC IDE, or use the ActionScript Compiler (ASC) from the command line.

When executed, this code would produce output similar to:

{3 4}
12
14
{5}
78.53981633974483
31.41592653589793

This example demonstrates how to implement interface-like behavior in ActionScript, allowing for polymorphism and the ability to work with different shapes through a common interface.