View comments | RSS feed

1.7 Interfaces

An interface defines a contract between an instance and code that uses that instance. When a class implements an interface, it guarantees that it will provide the methods declared in that interface. An implementing method must be declared public, in which case it will implement all unimplemented interface methods with the same identifier. An example of an interface follows:

interface Greetings {
    function hello()
    function goodmorning()
}

class Greeter implements Greetings {
    public function hello() { 
        trace("hello, world")
    }
    public function goodmorning() { 
        trace("goodmorning, world")
    }
}
var greeter : Greetings = new Greeter()
greeter.hello()

Comments


No screen name said on Mar 1, 2006 at 5:55 AM :
I'm still trying to understand the use of interfaces and then I saw this example and I'm more confused.

should:
var greeter : Greetings = new Greeter()

be:
var greeter : Greeter = new Greeter()

and if not, why?
Francis Cheng said on Mar 2, 2006 at 10:36 AM :
You can use either the class or the interface as a type annotation because both represent data types.
No screen name said on Mar 6, 2006 at 8:35 AM :
Usually, you may use the interface type. Thus you can use any object of a class implementing the interface, even if it didn't exist when the variable definition was written. That's the main reason (polimorfism) of interfaces, not multiple inheritance.
Joe@emeraldforest said on Feb 22, 2008 at 8:11 AM :
FOr me the biggest advantage of interfaces is the ability to group class methods.

Instead of testing every method for existence before using it, you just check to see if the class implements a certain interface that contains that method. If it does, you may use any of the methods in that interface without fear of it's non-existence. Then you can also set a behaviour to occur should the interface NOT be implemented.

Thus you should get into the habit of grouping methods into interfaces and if you want a class to have those methods, extend the interface and implement all the appropriate methods. It may seem a pain if you only need one of the 5 methods but it will save you lots of time later like I said earlier, in testing every stinking method for existence before calling it.

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/specs/actionscript/3/as3_specification9.html