Summary: A very brief introduction to the concepts of object-oriented programming with descriptions of encapsulation, inheritance, and polymorphism. Includes two new custom components that will run in the Flash player plugin.
Note: You are viewing an old version of this document. The latest version is available here.
| Note that all references to ActionScript in this lesson are references to version 3 or later. |
This tutorial lesson is part of a continuing series of lessons dedicated to object-oriented programming (OOP) with ActionScript.
There are several ways to create and launch programs written in the ActionScript programming language. Many of the lessons in this series will use Adobe Flex as the launch pad for ActionScript programs. An earlier lesson titled The Default Application Container provided information on how to get started programming with Adobe's Flex Builder 3. (See Baldwin's Flex programming website .) You should read that lesson before embarking on the lessons in this series.
One of the complicating factors in using Adobe Flex as the launch pad for ActionScript programs is the difficulty of understanding the relationships that exist between Flex and ActionScript. I recommend that you study the following lessons on Baldwin's Flex programming website that address that topic:
I recommend that you also study all of the other lessons on Baldwin's Flex programming website in parallel with your study of these ActionScript lessons. Eventually you will probably need to understand both technologies and the relationships that exist between them in order to become a successful ActionScript programmer.
Another complicating factor is knowing whether to use ActionScript code or Flex MXML code to achieve a particular objective. In many cases, either will do the job.
Insofar as this series of lessons is concerned, the emphasis will be on ActionScript code even in those cases where Flex MXML code may be a suitable alternative.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com .
If you Google this question, you will get hundreds of answers. Here is my answer along with an anecdotal description.
Unlike earlier programming styles,
Object-oriented programming is a programming style that mimics the way most people think and work .
If you have ever assembled a child's playscape in your back yard, this scenario should sound familiar to you.
When you opened the large boxes containing the playscape, hundreds of objects spilled onto the ground. Those objects may have consisted of braces, chains, swing seats, slides, screws, nuts, bolts, washers, climbing ropes, ladder rungs, and other assorted objects.
I will refer to the kind of object that I have described in the above list as atomic objects. What I mean by that is that they can't be easily subdivided into smaller objects.
If you were lucky, some of the objects in the box may not have been atomic objects. Instead they may have been pre-assembled arrangements of atomic objects such as a climbing net composed of individual ropes tied together to form a net.
Your job was to assemble those hundreds of atomic and non-atomic objects into a final object which you proudly referred to as "The Playscape."
It has been said that a successful object-oriented program consists of a bunch of cooperating software objects working together to achieve a specified behavior. The overall behavior of the program is the combination of behaviors of the individual objects. For example, some objects may acquire input data, other objects may compute and produce output data, while other objects may display the output data.
It could also be said that a playscape consists of a bunch of hardware objects working together to achieve a specified behavior. The overall behavior of the playscape is the combination of behaviors of the individual objects. For example, the behavior of some of the braces is to stand strong and not bend or break, while the behavior of a swing is to be flexible and move in a prescribed way.
One of the tasks of an object-oriented programmer is to assemble software objects into a model that often represents something that exists in the real world. For a very visual example, you might be asked to create an advertising web page showing an animated software model of the playscape that you assembled in your back yard. With the playscape, you were simply required to assemble the existing hardware objects. However, in the object-oriented programming world, you must do more than just assemble objects.
Getting back to the playscape, every one of the objects for the playscape was manufactured before being shipped to you. Even before that, each object was designed by someone and a set of manufacturing drawings was probably created so that the object could be mass produced in a high-volume manufacturing facility.
In OOP, there is a direct analogy to the manufacturing drawings of the hardware world. We call it a class . A class documents the specifications for the construction of a particular type of software object.
As an object-oriented programmer, you will typically have access to a large library of existing classes from which you can construct different types of software objects, such as buttons, sliders, etc. In addition, you will often need to design and define new classes from which you can construct new types of objects.
Although ActionScript and Flex provide a large class library from which you can construct objects (components) , you will probably need to create new custom components from time to time as well.
Flex/MXML can be used to create simple custom components but ActionScript is often needed to cause those components to have more interesting behavior.
Sometimes you can embed or include non-OO ActionScript code in a Flex MXML file to achieve the desired behavior. Often, however, you will need to create your new component almost entirely in ActionScript. You will need to understand OOP in order to do that.
An understanding of OOP is particularly important if you need to create a new component from scratch or create a new component by modifying the appearance and/or behavior of a component for which a class already exists.
I will provide an example of a new custom component that extends an existing component later in this lesson.
Therefore, if you plan to create rich internet applications, games, or iPhone applications using ActionScript, you will often need to understand OOP in order to create custom components that your clients find interesting.
Some languages such as C do not readily support OOP. Other languages such as C++ and ActionScript support OOP, but don't require you to use the object-oriented features of the language. Still other languages such as Java and C# require you to program using OOP techniques.
Because ActionScript does not enforce a requirement for your code to be object oriented (OO) , it is possible to learn to use major aspects of ActionScript without ever learning to use the object-oriented features. This approach simply requires you to learn how to use the rudimentary aspects of the language.
The real challenge to becoming an ActionScript programmer is not simply to learn the rudimentary aspects of the language. The real challenge lies in:
The first of these challenges can be met on a gradual basis. In other words, it is not necessary to memorize the entire class library to produce useful OO programs. However, it is necessary to learn how to use the library documentation to find what you need.
The remaining two challenges cannot easily be met on a gradual basis. Many aspects of OOP must be understood before a programmer can successfully write OO programs
An introductory description of OOP can be based on the guideline in Figure 1.
| Figure 1 . Guideline for OOP. |
|---|
| The solution to the problem should resemble the problem, and observers of the solution should be able to recognize the problem without necessarily knowing about it in advance. |
For example, an OO program that deals with banking transactions should be recognizable on the basis of the objects that it uses, such as deposit objects, withdrawal objects, account objects, etc.
Many "application frameworks" are written according to the OOP paradigm. Important among these is Adobe's Flex, which can be used to simplify the development of the graphical user interface (GUI) portions of ActionScript programs.
Flex makes it possible to use uncomplicated XML syntax to access and use the ActionScript class library. Adobe's Flash Builder 4 makes the process even more straightforward by providing a largely drag-and-drop visual development environment for creating the GUI portion of ActionScript programs.
All of the components that are available in Flex are objects created from classes in the ActionScript library. Those classes have names like Button , RadioButton , and NumericStepper (see Figure 2) .
Any object-oriented language must support three very important concepts:
We use these three concepts extensively as we attempt to model the real-world problems that we are trying to solve with our object-oriented programs. I will provide brief descriptions of these concepts in the remainder of this lesson and explain them in detail in future lessons.
Consider the steering mechanism of a car as a real-world example of encapsulation. During the past eighty years or so, the steering mechanism for the automobile has evolved into an object in the OOP sense.
In particular, most of us know how to use the steering mechanism of an automobile without having any idea whatsoever how it is implemented. All most of us care about is the interface , which we often refer to as a steering wheel. We know that if we turn the steering wheel clockwise, the car will turn to the right, and if we turn it counterclockwise, the car will turn to the left.
Most of us don't know, and don't really care, how the steering mechanism is actually implemented "under the hood." In fact, there are probably a number of different implementations for various brands and models of automobiles. Regardless of the brand and model, however, the human interface is pretty much the same. Clockwise turns to the right, counterclockwise turns to the left.
As in the steering mechanism for a car, a common approach in OOP is to "hide the implementation" and "expose the interface" through encapsulation.
Another important aspect of OOP is inheritance . Let's form an analogy with the teenager who is building a hotrod. That teenager doesn't normally start with a large chunk of steel and carve an engine out of it. Rather, the teenager will usually start with an existing engine and make improvements to it.
In OOP lingo, that teenager extends the existing engine, derives from the existing engine, inherits from the existing engine, or subclasses the existing engine (depending on which author is describing the process) .
Just like in "souping up" an engine for a hotrod, a very common practice in OOP is to create new improved objects by extending existing class definitions.
One of the major arguments in favor of OOP is that it provides a formal mechanism that encourages the reuse of existing programming elements. One of the mottos of OOP is "reuse, don't reinvent."
A third important aspect of OOP is polymorphism . This is a Greek word meaning something like one name, many forms . This is a little more difficult to explain in non-programming terminology. However, we will stretch our imagination a little and say that polymorphism is somewhat akin to the automatic transmission in your car. In my Honda, for example, the automatic transmission has four different methods or functions known collectively as Drive (in addition to the functions of Reverse, Park, and Neutral) .
As an operator of the automobile, I simply select Drive (meaning go forward) . Depending on various conditions at runtime , the automatic transmission system decides which version of the Drive function to use in every specific situation. The specific version of the function that is used is based on the current conditions (speed, incline, etc.) . This is somewhat analogous to what we will refer to in a subsequent tutorial lesson as runtime polymorphism .
OOP involves a whole new vocabulary (or jargon) which is different from or supplemental to the vocabulary of procedural programming.
For example the object-oriented programmer defines an abstract data type by encapsulating its implementation and its interface into a class .
One or more instances of the class can then be instantiated .
An instance of a class is known as an object .
Every object has state and behavior where the state is determined by the current values stored in the object's instance variables and the behavior is determined by the instance methods of the class from which the object was instantiated .
Inherited abstract data types are derived classes or subclasses of base classes or super classes . We extend super classes to create subclasses .
Within the program, the code instantiates objects (creates instances of classes) and sends messages to the objects by invoking or calling the class's methods (or member functions) .
If a program is "object oriented", it uses encapsulation , inheritance , and polymorphism . It defines abstract data types , encapsulates those abstract data types into classes , instantiates objects , and sends messages to the objects .
To make things even more confusing, almost every item or action used in the OOP jargon has evolved to be described by several different terms. For example, we can cause an object to change its state by sending it a message , calling its methods , or calling its member functions . The term being used often depends on the author who wrote the specific book that you happen to be reading at the time.
Hopefully most of this terminology will become clear as we pursue these lessons.
We have reached the point in this discussion where I should provide some examples of ActionScript 3 class definitions so that you can get a preview of what lies ahead.
The code beginning with the word public in Listing 1 is the definition of a very simple class named MyClass . I don't expect this code to mean much to you at this point. Suffice it to say that an object of this class is a new GUI component consisting of a Button object, a RadioButton object, and a NumericStepper object, all contained in a VBox object.
| Listing 1 . Class file named MyClass.as. |
|---|
|
The definition of the class creates a new data type, which is unknown to the compiler until it is defined by the programmer.
Two objects of the new class named MyClass are shown in Figure 2. You should be able to spot the Button object (rectangular) , the RadioButton object (circular) , and the NumericStepper object in each of the two MyClass objects.
| Figure 2 . Two objects of the class named MyClass. |
|---|
|
Normally you can't see a VBox object. You can only see the components that it contains. However, I included code in Listing 1 to set the background style of the VBox object to yellow to make it possible for you to visually separate the two new custom objects in Figure 2.
Listing 2 shows the Flex file that was used to instantiate the two objects of the class named MyClass and to display them in the Flash Player window in a browser.
| Listing 2 . Flex file named SimpleClass01.mxml. |
|---|
|
The two lines of code beginning with the words classes in Listing 2 cause the two new objects to be instantiated and displayed.
One of the standard Flex components is named TextArea . This component is an object of the ActionScript class having the same name.
As an example of creating a new custom component that extends an existing class, I will present and discuss a new custom component that extends the TextArea class. The new class is named NumericTextAreaA.
An object of the NumericTextAreaA class behaves just like an object of the standard TextArea class except that the new component will only accept numeric characters, the space character, the backspace character, and the return character. All other characters are rejected when the user attempts to type them into the text area.
Figure 3 shows the visual manifestation of an object of this class with two lines of numeric and space characters having been entered. (The entry of additional lines of text causes scroll bars to automatically appear.)
| Figure 3 . An object of the class named NumericTextAreaA. |
|---|
|
It is possible to create simple custom components by embedding ActionScript code in a Flex MXML file. However, I don't believe that it is possible to create an object with this behavior without defining a new ActionScript class. Even if it is possible, defining a new class is the approach that makes the most sense to me.
The MXML code beginning with cc in Listing 3 instantiates the object shown in Figure 3.
| Listing 3 . The file named NumericTextArea01.mxml. |
|---|
|
Listing 4 shows the class definition from which the object shown in Figure 3 was instantiated.
| Listing 4 . The class definition for NumericTextAreaA. |
|---|
|
There may be quite a lot of code in Listing 4 with which you are not familiar. However, it is not my purpose in writing this lesson to get into the details of defining classes in ActionScript, so I won't take the time to explain this code in this lesson. Suffice it to say that Listing 4 checks the character code associated with each keystroke in the text area and rejects all but the numeric characters, the backspace character, the space character, and the return key.
I will explain code like this in detail in future lessons. For now, simply accept this as an example of why you may need to learn OOP in order to advance your career as an ActionScript programmer.
If you have the Flash Player plug-in (version 9 or later) installed in your browser you should be able to run this program by clicking on NumericTextArea01 .
Enter some alphabetic and numeric text in the white box to see how the GUI component behaves. Click the "Back" button in your browser to return to this page when you are finished experimenting with the component.
If you don't have the proper Flash Player installed, you should be notified of that fact and given an opportunity to download and install the Flash Player plug-in program.
I will publish a list containing links to ActionScript resources as a separate document. Search for ActionScript Resources in the Connexions search box.
Module name: What is OOP and Why Should I Care?
Files: ActionScript0104.htm, ActionScriptXhtml0104.htm, ActionScript0104.cnxml
-end-