Anatomy of a Class

 <  Day Day Up  >  

A class is a collection of properties and methods. Properties define the data associated with a class, and methods operate on the data. Together they define the capabilities of the object instance that is generated by the class definition.

In ActionScript 2.0, a class is defined using the class keyword, a class name , and a code block defined by curly braces. For example, let's say you need to define a class that represents a loan. A loan could be used to represent a car loan, a student loan, or a home loan. In each case, the loan would be different based on the amount of the loan, the interest applied, and the term of the loan. Listing 2.1 defines the Loan class.

Listing 2.1. Pseudocode for the Class Definition
 class Loan {             //properties             principal; //loan amount             rate; //loan loan interest rate             term; //length of the loan             //methods             calculateMonthlyPayment(){             } } 

The name of the class must be the same as the name of the external file that contains the class. Anything defined within the curly brackets is considered a class member .

N OTE

All classes are defined in files that are stored external to the Flash document. The files are named with the class name and have the extension ".as".


Properties

A class can contain properties. Properties are variables that are defined within the class block. They are used to hold data of a specific type used by the class instance. They are also called instance variables .

The syntax of a property definition is shown in Figure 2.1:

Figure 2.1. Class property declaration.

graphics/02fig01.gif

The var keyword indicates a variable definition and the : separates the variable name from its data type. In ActionScript 2.0, case sensitivity and strict data typing are implemented, as shown in Chapter 1, "What's New in ActionScript 2.0?" What this means to you is that "principal" is not the same as "Principal." ActionScript 2.0 also implements strict datatyping. In the following example, principal is defined as a Number; therefore, it cannot be assigned "5.0" because "5.0" is treated as a string.

 var principal:Number = "5.0"; 

Note this valid assignment, however:

 principal = 5.0; 

Properties can also be declared and assigned a value in a single statement:

 var principal:Number = 5.0; 

N OTE

Another advantage of strict datatyping is that Flash automatically displays code hints for built-in objects when they are strictly typed.


Our Loan class needs several properties to hold the data that makes an individual loan unique. Listing 2.2 adds four class properties to the Loan class: principal , rate , term , and customerName .

Listing 2.2. Class Definition with Properties
 class Loan {        //properties  var principal:Number; //loan amount   var rate:Number; //loan interest rate   var term:Number; //length of the loan   var customerName:String; //name of loan customer  //methods } 

Variable Scope

By using the var keyword within the class block, you are defining the scope of the properties to be the class block. The class properties are available for the life of the instance; they are in scope when the instance is created and out of scope when the instance is destroyed . After the instance is created, class properties are called instance data.

Methods

Methods are operations that can be performed by an object. They are capable of taking data as arguments and returning data to the caller. Methods are also call functions. They define the operations that the instance can perform.

Figure 2.2 lists the components of a method declaration:

Figure 2.2. Class method declaration.

graphics/02fig02.gif

This method takes one argument and returns nothing. You can use this method to set the value of the principal property in the Loan class, as shown in Listing 2.3.

Listing 2.3. Class Definition with Methods
 class loan Loan {        //properties        var principal:Number; //loan amount        var rate:Number; //loan interest rate        var term:Number; //length of the loan        var customerName:String; //name of loan customer  //methods   function setPrincipal(thePrincipal:Number):Void{   this.principal = thePrincipal;   }  } setPrincipal(5.5); 

This method is used to set the instance data for principal and requires no return statement.

How About this ?

In ActionScript 2.0, this is a keyword that refers to the current executing scope, which is the container class instance. In the setPrincipal method, the keyword this referenced the class property, principal , from within the class. It enables you to use a relative path to reference class members .

Return Type

Listing 2.3 used the keyword Void to indicate that this method does not return any data to the caller. However, what if you wanted to return data to the calling code? For example, the Loan class needs a method to calculate a monthly payment. The method returns the value and it requires more information to do the calculation. In Listing 2.4, the getMonthlyPayment() method requires data to do the calculation. thePrincipal and theTerm are passed in as method arguments and have a return statement.

Listing 2.4. Class Definition with Method Return Statement
 class Loan {        //properties        var principal:Number; //loan amount        var rate:Number; //loan interest rate        var term:Number; //length of the loan        var customerName:String; //name of loan customer       //methods       function setRate(theRate:Number):Void{             this.rate = theRate;       }  function getMonthlyPayment(thePrincipal:Number, theTerm:Number):Number{   var monthlyPayment:Number;   //calculate payment     return monthlyPayment;   }  } 

The return type in the method signature is the datatype of the return value. The data returned must match the datatype declared in the return type of the method. Listing 2.5 defines the getNumber() method with a valid signature and return variable, as opposed to Listing 2.6, where the return type doesn't match the signature return type.

Listing 2.5. Valid Signature and Return
 function getNumber():Number{        var num:Number;        return num; } 
Listing 2.6. Invalid Signature and Return
 function getNumber():Number{        //will generate a compiler error :        //'The expression returned must match the        // function's return type.'        var numStr:String;        return numStr; } 

If the method returns nothing, the return type is Void . Although you can omit the return type of a method, it is highly recommended as a best practice to always include the return type, even when there is nothing being returned.

Any valid datatype can be returned from a method. Number , String , and Boolean are all valid datatypes. A class is also considered a valid datatype, so it also can be returned by a method.

Method Name

The method name distinguishes one method from another in a class. In ActionScript, each method name must be unique.

N OTE

Some object-oriented languages, such as Java, permit method overloading, which means that you can have two methods named the same with different signatures. However, this is not the case in ActionScript 2.0. Each method name must be unique within one class.


The Constructor

Currently, you are missing a means to create an instance of the class. An instance is to a class what a house is to a blueprint. It is the physical manifestation of the object defined by the class. In ActionScript 2.0, you can create a special method to create an instance of a class. It is called a constructor .

A constructor is a special kind of method used to create an object instance. The constructor method is named the same as the class name (including the case). Listing 2.7 adds a constructor to the Loan class definition:

Listing 2.7. Class Definition with Constructor
 class Loan {        //properties        var principal:Number; //loan amount        var rate:Number; //loan interest rate        var term:Number; //length of the loan        var customerName:String; //name of loan customer  function Loan(){  trace("in Loan constructor");              //initialize the loan object  }  //methods } 

As stated, the constructor is a special kind of method that breaks many of the rules of a method. For example, a constructor doesn't require a return type. As a matter of fact, if it has one, it generates a compiler error.

The constructor is generally used to initialize an object. If the class has no constructor, the compiler adds a "no-argument" constructor. Thus, as long as your constructor doesn't require any arguments, you can omit the constructor and use the default, " no-argument " constructor.

What's in a Name?

There are different approaches to naming class members. On the one hand, verbose naming of class members makes your code easier to read and maintain. For example, a variable to hold an interest rate for a mortgage might be called annualPercentageRate . Although it is easy to read, it may be prone to typos because of its length. On the other hand, apr might not provide enough information to the programmer.

Whether you choose verbose or abbreviated or somewhere in between, it's a good idea to have some structure. The following subsections give guidelines you should follow when naming class member identifiers.

Naming Identifiers

An identifier is a name given to a property, variable, class, or method. Identifiers adhere to the following rules:

  • They are case sensitive.

  • They begin with a letter or underscore (_) and subsequent characters can be digits or letters .

  • They have no maximum length.

  • They cannot be a reserved word.

There are some words within ActionScript that are reserved words, which means that they have a specific use within the language. These words cannot be used as identifiers for properties/variables, methods, or class names . The following is a list of all ActionScript keywords:

break

case

class

continue

default

delete

dynamic

else

extends

for

function

get

if

implements

import

in

instanceof

interface

new

private

public

return

set

static

switch

this

typeof

var

Void

while

with

Suggested Naming Conventions

You should have a naming convention when building any application, especially when you are using a well- formed language with conventions such as case sensitivity and strict datatyping. Now, more than ever, a naming convention in Flash saves you time and headaches . Table 2.1 has some suggested conventions.

Table 2.1. Naming Conventions

I TEM

D ESCRIPTION

E XAMPLE

Class

A class name begins with a capital letter.

Loan

If a class name is comprised of more than one word, capitalize the first letter of each word.

Customer

Variables and properties

Variables always begin with a lowercase letter.

principal monthlyPayment

If a variable is comprised of more than one word, every word after the first begins with a capital letter.

 

Methods

Methods typically begin with a word that is a verb whose first letter is lowercase.

addItem()

getLastName()

If a method is comprised of more than one word, every word after the first begins with a capital letter.

 
 <  Day Day Up  >  


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

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