Understanding Polymorphism 101

Polymorphism is all about “interchangeable” objects. According to Thinking in Java (2nd ed):

When dealing with type hierarchies, you often want to treat an object not as the specific type that it is, but instead as its base type. This allows you to write code that doesn’t depend on specific types.

1. Set type to interface instead of an abstract/concrete class is considered a better OO approach. A fancy way of rephrasing this is to program to interfaces instead of concrete implementations. Other approaches include inheritance and composition.

var reader:IReader = new FileReader(url);

In the preceding code, we set type of reader to its interface IReader instead of its own type FileReader. This way we “program to the interface”.

2. Interfaces can extend other interfaces (but not abstract or concrete classes). All the classes that implement an interface should also implement all the interfaces the interface extends. A convenient way of implementing an interface is to extend an abstract/concrete class that already implements it. Example:

package test
import flash.events.IEventDispatcher;
public interface IReader extends IEventDispatcher{}

package test
import flash.events.EventDispatcher;
import test.IReader;
public class AbstractReader extends EventDispatcher implements IReader
public function read():void
trace("i am reading!");


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: