Posts Tagged polymorphism

How to use interface in ActionScript 3

There are a lot of good ActionScript 3 books out there, but in most of them all the examples about inheritance, composition, interface, polymorphism and more complex object oriented principles are done using data classes. It’s good to explain the principles, but when you are ready to code some actual classes in Flash, some problems start to arise. Most of my problems come from the fact that 90% of the time I am coding classes that are a visual representation of something. So these classes extends the Sprite or MovieClip class.

So I was coding this game class where I have multiple kind of monsters but I want to use the same functions without checking what kind of monster it is. This is a case where polymorphism comes in handy. The thing is I didn’t do my classes of monster using inheritance (which maybe I should have done), so in order to use polymorphism, I have to create an interface with the public methods common to all my monster classes. So I open the Colin Moock book and start looking at how to code interfaces. Here is a list of quick facts that will help you while doing so.

  • You have to list all public methods that will be common for the classes that implements this interface;
  • You do so by writing the definition of the function, its name, its parameters and its return type;
  • You don’t have to open and close curly braces after the method definition
  • You don’t specify if the method is private, public or protected (that’s kind of obvious but I did that mistake)
  • interface can only extend other interfaces
  • a class can implement more than one interface

So here is an example of an interface in As3:

  public interface IMonster {
    function getShot(damage:uint):void;
    function getCanShoot():Boolean;

Here is how my visual class implements this interface while also extending the MovieClip class:

public class spriteMouton extends MovieClip implements IMonster{

It is important that you put the extend keyword before the implement keyword.

So most of what I just wrote about was details about interfaces, but when you start coding, all these details are important to know.

Here are two more article I wrote about interfaces:

, ,