4.1 Defining Classes

 <  Day Day Up  >  

A class is a template for the creation of objects (or, synonymously, instances ). Classes are the building blocks of an object-oriented program. Every object-oriented application includes at least one class, and typical applications include several or dozens of classes. From classes, a program generates the objects that determine the things the program can do.

We saw earlier that classes are used to group properties and methods into a coherent bundle. A typical class might define a spaceship or a scrollbar in terms of how it looks, what it does when the user clicks on it, or how it interacts with other objects.

To create, or define , an ActionScript 2.0 class, we use a class declaration, which starts with the class keyword, as follows :

 class   ClassIdentifier   { } 

where ClassIdentifier is the name of the class (which, by convention, should start with a capital letter). For example, the following code defines a class named Box , albeit one that doesn't do anything interesting yet:

 class Box { } 

We'll use the Box class as an example throughout this chapter. Eventually, our Box will represent and control an on-screen rectangular shape. You might use a similar class in a drawing-tool application. The Box class is intentionally generic, allowing you to map its concepts onto your own classes. In subsequent chapters, we'll explore more applied scenarios.

A class definition must reside in an external plain text file that has the extension .as . Use of the class keyword anywhere else ”such as on a keyframe or a button ”generates a compile-time error. Furthermore, each .as file can contain only one class definition and must have a filename exactly matching the name of the class it contains (case sensitivity matters!).


For example, the Box class must be stored in a file named Box.as . If Box.as erroneously contains a class named, say, Circle , the compiler generates the following error when the Box class is instantiated :

 The class 'Circle' needs to be defined in a file whose relative  path is 'Circle.as'. 

We'll learn more about the file structure of an object-oriented Flash application in Chapter 5 and Chapter 11. For now, our focus is mainly on the code that goes into a class.

figs/as1note.gif ActionScript 1.0 had no formal class statement. Classes were defined using the function statement, as in:

 function Box ( ) { } 

ActionScript 1.0 class definitions were allowed anywhere that code was legal (e.g., a frame, a button, or a movie clip) but were conventionally stored in external .as files and brought into a .fla file using the #include directive, which is not required in ActionScript 2.0.

Everything between the curly braces in a class declaration constitutes the class definition block , or more informally, the class body . The class body can contain:

  • A constructor function (used to initialize instances of the class)

  • Variable definitions (the class's properties)

  • Function definitions (the class's methods)

  • #include directives, which can include files containing properties, methods, and constructor functions

  • Metadata tags used in Flash MX 2004 components

  • Comments

Nothing else is permitted ”class definitions cannot be nested, and no other code can appear in a class definition. For example, the following code is illegal because the if statement is not one of the six legal items listed:

 class Box {   if (100 == 10*10) {     trace("One hundred is ten times ten");   } } 

In other words, you cannot place raw code directly into a class statement. All code must either define a property or be part of a method or constructor function.

However, you can work around this limitation by adding a so-called class method that runs the first time an instance is constructed , but never again. The following code demonstrates the approach, using techniques we haven't yet covered. If the code seems foreign to you, try returning to it when you've finished reading this chapter:

 class Box {   private static var inited:Boolean = false;      public function Box ( ) {     if (!inited) {       init( );     }   }   private static function init( ):Void {     if (100 == (10*10)) {       trace("One hundred is ten times ten");     }     inited = true;   } } 

In ActionScript, a class's methods and properties are referred to collectively as its members . For example, we might say " radius is not a member of Box ," meaning that the Box class does not define any methods or properties named radius .


Further, the term instance member refers to either an instance property or an instance method (covered later), while the term class member refers to either a class property or a class method (also covered later). The terms static member , static property , and static method are sometimes used as synonyms for the terms class member , class property , and class method . We'll learn much more about instance and class members throughout this chapter.

4.1.1 Class Attributes

Class definitions can be modified with one or both of two attributes : dynamic and intrinsic . Attributes dictate how a class and its instances can be used in a program. Attributes must be listed before the keyword class in a class definition. For example, to add the dynamic attribute to the Box class, we'd use:

  dynamic  class Box { } 

ActionScript 2.0 does not support ECMAScript 4's final attribute (which prevents a class from being subclassed), nor does it support a Java-style abstract modifier (which prevents instances of a class from being created). For one way to simulate an abstract class, see "Constructor Functions (Take 2)," later in this chapter.

4.1.1.1 The dynamic attribute

By default, a class's members must be defined exclusively within the class statement. Any attempt to add a property or method to an individual instance of a class or the class itself from outside the class definition causes a compile-time error. However, when a class is defined with the dynamic attribute, new properties and methods can legally be added both to the class's instances and to the class itself. For example, suppose we define the Box class without the dynamic attribute, as follows:

 class Box { } 

Further, suppose we create a Box instance and attempt to give it a new property named size :

 var b:Box = new Box( ); b.size = "Really big"; 

When that code is compiled, the following error appears in the Output panel:

 There is no property with the name 'size'. 

because the size property isn't declared within the Box class definition, and properties cannot be added dynamically, so the compiler thinks you are trying to access a nonexistent property.

But if we add the dynamic attribute to the class definition:

  dynamic  class Box { } 

then the preceding size property addition is allowed and does not cause an error at compile time. Similarly, when the Box class is not dynamic, the following attempt to define a new class property is illegal:

 // Illegal when   Box   class is not dynamic. Box.classPurpose = "Represent a four-sided figure"; 

But again, when the Box class is dynamic, the preceding property definition is legal.

The size and classPurpose properties are examples of dynamic properties , which can be added at runtime only to classes declared with the dynamic attribute (and to instances of such classes).

Generally speaking, you should not rely on dynamic classes in your application development. It's considered bad form to augment a single object with a new dynamic property or method. If the property or method rightly applies to all instances of the class, add it to the class definition. If the property or method does not apply to all instances of the class, the following approach is preferred over using a dynamic class:

  1. Create a subclass of the original class.

  2. Add the new property or method to the subclass definition (i.e., don't add it dynamically at runtime).

  3. Create the object as an instance of the subclass instead of the superclass.

The dynamic attribute is provided primarily to give the built-in ActionScript classes special behavior. For example, the MovieClip and Object classes are both defined as dynamic , which allows all MovieClip and Object instances to take on new properties and methods. If the MovieClip class were not dynamic, any attempt to create a variable on a Flash timeline frame would fail. Similarly, the Array class is declared dynamic so that any array can define named elements (in addition to numbered elements). Note, however, that even though the built-in Object class is dynamic, a compiler bug in Flash MX 2004 makes attempts to add class properties to the Object class fail when they occur in a class body. For example, if the following line of code appears in any class body, the compiler generates an error:

 Object.someProp = "Hello world"; 

In general, subclasses of a dynamic class are also dynamic. This guarantees that features in the superclass that rely on the dynamic class definition work properly in any subclass. However, subclasses of the MovieClip and Object classes are, by default, not dynamic, because every class is a subclass of Object, but not all classes should be dynamic by default. With the exception of MovieClip and Object , there is no way to make a subclass of a dynamic class nondynamic.

figs/as1note.gif In ActionScript 1.0, all classes were effectively dynamic. Properties and methods could be added to any instance or class at runtime without error.

4.1.1.2 The intrinsic attribute

The intrinsic attribute is used only when distributing a compiled class without also distributing the class's source code, such as in the case of the built-in Flash Player classes. A class defined with the intrinsic attribute includes no method bodies or property values; it simply specifies property and method names and datatypes for the sake of compile-time type checking.

For example, the following code shows the intrinsic class definition for the Flash Player's built-in LoadVars class:

 dynamic intrinsic class LoadVars {         var contentType:String;         var loaded:Boolean;         var _customHeaders:Array;                  function load(url:String):Boolean;         function send(url:String,target:String,method:String):Boolean;         function sendAndLoad(url:String,target,method:String):Boolean;         function getBytesLoaded( ):Number;         function getBytesTotal( ):Number;         function decode(queryString:String):Void;         function toString( ):String;         function onLoad(success:Boolean):Void;         function onData(src:String):Void;         function addRequestHeader(header:Object, headerValue:String):Void; } 

The LoadVars class is compiled into the Flash Player itself, so its source code is not available to the ActionScript compiler at authoring time. The compiler uses the preceding intrinsic class definition to perform type checking on LoadVars instances at compile time. The Flash MX 2004 and Flash MX Professional 2004 authoring tools include intrinsic class definitions for all built-in classes and objects. For details, see "Datatype Information for Built-in Classes" in Chapter 3.

We'll learn more about intrinsic class definitions in Chapter 14.

 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

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