Implement an Interface : interface « Class « Flash / Flex / ActionScript






Implement an Interface

 

package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){

        var srcInstance:ShapeContainer = new ShapeContainer(200, 200);
        
        var cirA:Circle = new Circle(0, 0, 50);
        var cirB:Circle = new Circle(0, 0, 400);
        var sqA:Square = new Square(0, 0, 100);
        var sqB:Square = new Square(0, 0, 200);
        
        var bAdded:Boolean;
        
        bAdded = srcInstance.addShape(cirA);
        trace(bAdded);
        bAdded = srcInstance.addShape(cirB);
        trace(bAdded);
        bAdded = srcInstance.addShape(sqA);
        trace(bAdded);
        bAdded = srcInstance.addShape(sqB);
        trace(bAdded);
    }
  }
}
interface IShape {

  function getDimensions():Object;

}

class Circle implements IShape{

  private var _nX:Number;
  private var _nY:Number;
  private var _nRadius:Number;

  public function Circle(nX:Number, nY:Number, nRadius:Number) {
    nX = nX;
    nY = nY;
    nRadius = nRadius;
  }

  public function getDimensions():Object {
    return {width: 2* _nRadius, height: 2  * _nRadius};
  }

}
class Square implements IShape {

  private var _nX:Number;
  private var _nY:Number;
  private var _nSide:Number;

  public function Square(nX:Number, nY:Number, nSide:Number) {
    _nX = nX;
    nY = nY;
    nSide = nSide;
  }

  public function getDimensions():Object {
    return {width: _nSide, height: _nSide};
  }

}
class ShapeContainer {

  private var _aShapes:Array;
  private var _nWidth:Number;
  private var _nHeight:Number;

  public function ShapeContainer(nWidth:Number, nHeight:Number) {
    _nWidth = nWidth;
    _nHeight = nHeight;
    _aShapes = new Array();
  }

  public function addShape(shObject:IShape):Boolean {
    if(shObject.getDimensions().height > _nHeight) {
      return false;
    }

    var nSum:Number = 0;
    for(var i:Number = 0; i < _aShapes.length; i++) {
      nSum += _aShapes[i].getDimensions().width;
    }

   
    if(nSum + shObject.getDimensions().width > _nWidth) {
      return false;
    }
    else {
      _aShapes.push(shObject);
      return true;
    }
    }

}

        








Related examples in the same category

1.Interface Syntax and Use
2.Creating Interfaces
3.Extends an interface
4.Interface Inheritance
5.Implementing an Interface
6.Implement interface
7.Implement two interface