234 Classes
Encapsulation
In elegant object-oriented design, objects are seen as “black boxes” that contain, or
encapsulate, functionality. A programmer should be able to interact with an object by knowing
only its properties, methods, and events (its programming interface), without knowing the
details of its implementation. This approach enables programmers to think at higher levels of
abstraction and provides an organizing framework for building complex systems.
Encapsulation is why ActionScript 2.0 includes, for example, member access control, so
details of the implementation can be made private and invisible to code outside an object.
The code outside the object is forced to interact with the object’s programming interface
rather than with the implementation details (which can be hidden in private methods and
properties). This approach provides some important benefits; for example, it lets the creator
of the object change the object’s implementation without requiring any changes to code
outside of the object—that is, as long as the programming interface doesn’t change.
For more information on encapsulation, see “About using encapsulation” on page 261.
Polymorphism
OOP lets you express differences between individual classes using a technique called
polymorphism, by which classes can override methods of their superclasses and define
specialized implementations of those methods. In Flash, subclasses can define specialized
implementations of methods inherited from its superclass but cannot access the superclass’s
implementation as in other programming languages.
For example, you might start with a class called Mammal that has
play() and sleep()
methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The
subclasses override the
play() method from the Mammal class to reflect the habits of those
particular kinds of animals. Monkey implements the
play() method to swing from trees; Cat
implements the
play() method to pounce at a ball of yarn; Dog implements the play()
method to fetch a ball. Because the
sleep() functionality is similar among the animals, you
would use the superclass implementation.
For more information on polymorphism, see Chapter 8, “Inheritance,” on page 301 and
“Using polymorphism in an application” on page 308.