Chapter 12. Objects and Classes

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Part I:  ActionScript Fundamentals

This chapter covers object-oriented programming (OOP), which is new territory for many readers. We'll cover OOP methodology and terminology, using applied examples to make it all concrete. For the benefit of both experienced programmers and new programmers who appreciate a broad perspective, we'll compare ActionScript's OOP practices with those of Java and other languages. Experienced object-oriented programmers who simply want an overview of ActionScript's OOP syntax may want to skip directly to the Section 12.9 at the end of this chapter.

If you're new to object-oriented programming, you may have heard that OOP is some big mystery or that it's difficult to understand. Quite to the contrary, the concepts are highly intuitive, and the OOP process is much easier than you may have been led to believe. At its heart, OOP simply means that you treat portions of your program as self-contained modules called "objects." By "self-contained," we don't mean that objects are isolated, but rather that they can be independent of each other, and that you can use an object without worrying about its internal details. OOP concepts are easy to grasp once you realize that everything you deal with in the real world is a self-contained object. Your dog, your parents, your car, and your computer are all self-contained objects meaning that they do some things independently and do other things at your request, even if you don't know the inner details of how they work.

You don't have to be a biologist to get your dog to fetch a stick; you don't need to be a mechanical engineer to drive your car; you don't need to be a psychoanalyst to interact with your parents; and, rumors to the contrary, you don't need to be a computer scientist to check your email. All you need to know is the commands an object is willing to obey (which are called methods) and the results those commands produce. For example, if you press the gas pedal of your car, you expect the car to accelerate. If you tell your dog to sit, you expect him to sit. Armed with this commonsense context of what an object is in the real world, let's see how to relate these concepts to ActionScript.

The classic example of a programming object is a bouncing ball. Like a real ball, a ball object can have properties that represent its attributes, such as its radius, color, mass, position, and bounciness (elasticity). To represent our bouncing ball in a program, we'll create a ball object with a radius property, a color property, and so forth. The properties of an object represent its state at any given time, but some of its properties change over time. For example, to make our ball move, we need to simulate Newton's laws of motion. That is, we need to describe in computer terms how a ball moves over time. In the simplest case, recalling that speed multiplied by time equals distance, we can determine a ball's horizontal position in the future using this equation:

Position = Speed * Time

We can translate this equation into ActionScript that calculates the ball's new position:

ball.xPosition += ball.xVelocity * elapsedTime;

This equation starts with the ball's current position and adds the distance it has traveled (based on its velocity and the elapsed time) to come up with the new position.

An object's behaviors are simply the things it can do or the services it can perform (one of our ball's behaviors is its ability to move). To describe an object's behaviors in code, we create so-called methods, which are simply the functions that implement an object's behaviors.

For example, we might create a move( ) method on our ball object that uses the preceding equation. Therefore, methods can be thought of as the commands that an object obeys. Of course, an object can have multiple methods. Let's say we want to make our ball bounce. We can create a bounce( ) method that reverses the ball's direction and reduces its speed (our ball isn't perfectly elastic). The bounce( ) method might implement this equation:

ball.xVelocity =  -(ball.xVelocity) * 0.95   // Ball is 95% elastic

Before getting into the esoterica of how to create objects, add properties, and implement methods, let's formalize some of our definitions. An object is a data structure that groups together related properties (variables) and methods (functions). An object typically encapsulates its behaviors, meaning that the internal details of how it performs its functions are not necessarily visible outside the object. Instead, a program interacts with an object via its so-called interfaces (i.e., methods that are publicly accessible outside the object). The rest of the program doesn't have to worry about how an object does what it does; instead, the program provides inputs to the object and checks the outputs (results) when applicable.

You'll also hear talk of classes and instances. A class is a generic object category, and an instance is a specific case (i.e., a copy) of the class of object. For example, your particular pet dog is an instance of the generic Dog class. All dogs in the Dog class bark and have four legs, but your specific dog has its own particular values for the height, weight, and color properties used to describe dogs. If you've seen a three-legged dog and therefore just objected to the assertion that "all dogs have four legs," you're already understanding OOP a class should accommodate all possible variations of its instances. Hence, to satisfy your objection to the Dog class design, you could add a numberOfLegs property that would be set separately for each individual Dog object.

Object-oriented programming (OOP) is merely the name given to programs that make use of objects. Objects and OOP are so intrinsic to ActionScript that we've already used them, perhaps without your realizing it. A movie clip is a familiar object in Flash, and like all objects, it is implemented as a collection of properties and methods. When we determine the height of a movie clip using someClip._height, we're accessing that clip object's _height property. And when we tell a movie clip to play using someClip.play( ), we're invoking that clip object's play( ) method.

Typically, all instances of an object class share the same methods and property names; it is the property values of each instance that distinguish it from other instances of the same class.

Whether we create objects ourselves or use those built into ActionScript, OOP keeps different parts of a program cleanly separated from one another (encapsulated ) and allows them to interoperate without knowing the internal details of other objects. This allows an object to change its internal functionality without adversely affecting other portions of the program that rely on the object, so long as the object's public methods (i.e., its interfaces to the outside world) don't change. Returning to our ball object, for example, we don't care if the laws of physics change the behavior of our ball's motion. We just call the ball's move( ) method and let the object itself worry about the details.

Another nice feature of OOP is that we can treat different objects that have different behaviors in a uniform manner, as long as they implement methods of the same name. For example, suppose we have a circle object and a square object. As long as both objects implement a getArea( ) method that returns the shape's area, we can call their getArea( ) methods without worrying about how each object calculates its own area.

In this chapter, you'll learn how to make a basic object and how to define a category of objects (i.e., a class). Once you're comfortable with the basics, you'll learn how to use inheritance to share common characteristics between classes. For example, we might implement a Horse class that, along with our Dog class, is a descendant of the Mammal class. The Mammal class could implement methods and properties common to all mammals, such as the fact that they have hair, give milk, are warm-blooded, and have (up to!) four legs. Thus, inheritance can be used to create a "family tree" of related classes. Later on, you'll also learn how OOP is used to control the Flash environment through ActionScript's built-in objects and classes.

Note that not all objects represent some physical aspect of a Flash movie. At the end of this chapter, we'll show how to implement our multiple-choice quiz using OOP. We'll use objects of the Quiz, Question, and QuizGUI classes, of which the first two are abstract concepts, not physical things, in the movie. Our Quiz class, rather than bouncing movie clips around the screen, encapsulates all the behaviors of a typical quiz adding questions, setting the title, setting the user's answer for a particular question, and so on. Even ActionScript itself uses objects to represent intangible things, such as times, dates, or the formatting applied to a text field.

Finally, bear in mind that ActionScript is quite flexible and does not force OOP on you. You can use OOP in only part of your program, or you can use it to structure everything you do. This flexibility can cause confusion for both experienced and new OOP programmers. Java developers, for example, expect everything in a program to be built as a class, which is possible, but not required in Flash. New OOP programmers, on the other hand, wonder how much OOP they should use to build what they want to build. In this chapter, we'll work towards the Java mentality, where everything in a program is represented as an object. Even if this never becomes your approach to Flash development, the exposure to rigorous OOP should enrich your understanding of objects and Flash at any level. If you're new to OOP, consider using objects whenever you create more than one of something; for example, fifteen balls, ten enemies, or two kinds of quizzes (multiple-choice or fill in the blank).

I hope that this introduction has shed some light on objects and OOP. Now let's dive in to the specifics.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net