Understanding inheritance and interfaces

You can use the extends keyword to create subclasses of an interface. This can be very useful in larger projects for which you might want to extend (or subclass) an existing interface and add additional methods. These methods must be defined by any classes implementing that interface.

One consideration you need to make when extending interfaces is that you receive error messages in Flash if multiple interface files declare functions with the same names but have different parameters or return types.

The following example demonstrates how you can subclass an interface file using the extends keyword.

To extend an interface:

  1. Create a new ActionScript file, and then save it as Ia.as.
  2. In Ia.as, type the following ActionScript code into the Script window:
    interface Ia {
        public function f1():Void;
        public function f2():Void;
    }
    
  3. Save your changes to the ActionScript file.
  4. Create a new ActionScript file and save it as Ib.as in the same folder as the Ia.as file you created in step 1.
  5. In Ib.as, type the following ActionScript code into the Script window:
    interface Ib extends Ia {
        public function f8():Void;
        public function f9():Void;
    }
    
  6. Save your changes to the ActionScript file.
  7. Create a new ActionScript file and save it as ClassA.as in the same directory as the two previous files.
  8. In ClassA.as, type the following ActionScript code into the Script window:
    class ClassA implements Ib {
        // f1() and f2() are defined in interface Ia.
        public function f1():Void {
        }
        public function f2():Void {
        }
        
        // f8() and f9() are defined in interface Ib, which extends Ia.
        public function f8():Void {
        }
        public function f9():Void {
        }
    }
    
  9. Save your class file and click the Check Syntax button above the Script window.

    Flash doesn't generate any error messages as long as all four methods are defined and match the definitions from their respective interface files.

NOTE

Classes are only able to extend one class in ActionScript 2.0, although you can use classes to implement as many interfaces as you want.

If you want your ClassA class to implement multiple interfaces in the previous example, you would simply separate the interfaces with commas. Or, if you had a class that extended a superclass and implemented multiple interfaces, you would use code similar to the following:

class ClassA extends ClassB implements Ib, Ic, Id {...}.