O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variables and Values

In ActionScript, every object is considered a single, self-contained piece of data (i.e., information) known as a value. Apart from objects, the only other legal values in ActionScript are the special values null and undefined, which represent the concept of "no value." A variable is an identifier (i.e., a name) associated with a value. For example, a variable might be the identifier submitBtn associated with an object representing a button in an online form. Or a variable might be the identifier productDescription associated with a String object that describes some product.

Variables are used to keep track of information in a program. They give us a means of referring to an object after it is created.

Variables come in four varieties: local variables, instance variables, dynamic instance variables, and static variables. We'll study the first two varieties now, and the remaining two varieties later in this book.

Local Variables

Local variables are used to track information temporarily within the physical confines of a constructor method, an instance method, a static method, or a function. We haven't studied instance methods, static methods, or functions yet so for now we'll focus on local variables in constructor methods.

To create a local variable within a constructor method, we use a variable definition, as shown in the following generalized code. Notice that the definition starts with the keyword var and, by convention, ends in a semicolon, as do all directives that do not include a block statement. The semicolon indicates the end of the directive, much like the period at the end of a sentence in a natural language.

class SomeClass {
  public function SomeClass () {
    var identifier = value;
  }
}

In the preceding code, identifier is the local variable's name, and value is the value associated with that variable. Together, the equals sign and the value are known as the variable initializer because they determine the initial value of the variable.

Tip

Associating a variable with a value is known as assigning, setting, or writing the variable's value.

When the variable initializer is omitted, ActionScript automatically assigns the variable a default value. Default values for variables are discussed in Chapter 8.

A local variable can be used within the method or function that contains its definition only. When the method or function finishes executing, the local variable expires and can no longer be used by the program.

Let's create a local variable to refer to the VirtualPet object we created earlier in the VirtualZoo constructor. We'll name the local variable pet, and we'll use an initializer to associate it with the VirtualPet object. Here's the code:

package zoo {
  public class VirtualZoo {
    public function VirtualZoo () {
      var pet = new VirtualPet;
    }
  }
}

Having associated the local variable pet with a VirtualPet object, we can now use that variable to refer to, and therefore control, that object. However, currently our VirtualPet object can't actually do anything because we haven't programmed its functionality. We'll start to rectify that shortcoming in the next section by giving pets the ability to have nicknames.

Instance Variables

Earlier we learned that a class describes the characteristics and behavior of a particular type of object. In object-oriented programming terms, a "characteristic" is a specific piece of information (i.e., value) that describes some aspect of an object—such as its width, speed, or color. To keep track of an object's characteristics, we use instance variables.

An instance variable is a variable attached to a particular object. Typically, each instance variable describes a characteristic of the object to which it is attached. For example, an instance variable might be the identifier width associated with the value 150, describing the size of the button object in an interface. Or, an instance variable might be the identifier shippingAddress associated with the value "34 Somewhere St," describing the destination of a product-order object.

Instance variables are created using variable definitions directly within class definitions, as shown in the following generalized code:

class SomeClass {
  var identifier = value;
}

Adding an instance variable definition to a class definition causes that variable to be automatically attached to each instance of the class. As with local variables, the initializer of an instance variable definition specifies the initial value of the instance variable. However, because instance variables are set independently for each individual instance of a class, the initial value of an instance variable is very often omitted and assigned later in the program.

As an example, let's add an instance variable to the VirtualPet class that tracks the nickname of each VirtualPet object. We'll call our instance variable petName. Here's the code:

package zoo {
  internal class VirtualPet {
    var petName = "Unnamed Pet";
  }
}

As a result of the preceding code, the instance variable petName is automatically attached to each new instance of the VirtualPet class. The initial value of petName for all VirtualPet instances is "Unnamed Pet." However, once each VirtualPet instance is created, a new, custom value can be assigned to its petName variable.

To assign an instance variable a new value, we use the following generalized code:

object.instanceVariable = value

In the preceding code, object is the object whose instance variable will be assigned a value, instanceVariable is one of object's instance variables (as defined by object's class), and value is the value to assign.

Let's use the preceding technique to assign a nickname to the VirtualPet object we created earlier in the VirtualZoo constructor. Here's the code as we last saw it:

package zoo {
  public class VirtualZoo {
    public function VirtualZoo () {
      var pet = new VirtualPet;
    }
  }
}

According to the generalized code for assigning an instance variable a new value, we need to start by referring to an object. In this case, we use the local variable pet to refer to the desired VirtualPet instance:

pet

Next, we write a dot:

pet.

Then, we write the name of the instance variable whose value we wish to assign—in this case, petName:

pet.petName

Finally, we write an equals sign, then the value we wish to assign to the instance variable. Let's use "Stan":

pet.petName = "Stan"

Isn't that cute? Our pet has a name. We're making progress.

Here's the code as it appears in our program:

package zoo {
  public class VirtualZoo {
    public function VirtualZoo () {
      var pet = new VirtualPet;
      pet.petName = "Stan";
    }
  }
}

In the preceding code, notice that the petName instance variable, which is defined in the VirtualPet class, is set through a VirtualPet instance from within the VirtualZoo class. The petName instance variable is, therefore, said to be accessible to code in the VirtualZoo class. When a class makes its instance variables accessible to code in other classes, it is conceptually allowing those classes to modify the characteristics of its instances. The nickname of a pet is a characteristic that naturally lends itself to external modification. However, some instance variables represent characteristics that should not be modified outside the class in which they are defined. For example, later in this chapter we'll create an instance variable, caloriesPerSecond, that represents the speed with which a pet digests its food. If an inappropriately small or large value is assigned to caloriesPerSecond, a pet might starve instantly or never grow hungry. Hence, to prevent external code from assigning an inappropriate value to caloriesPerSecond, we must limit access to that variable. To limit access to a variable, we use access-control modifiers.

Access-control modifiers for instance variables

An instance variable's access-control modifier controls that variable's accessibility in a program. The access-control modifiers available for instance variable definitions are public, internal, protected, and private. The public and internal modifiers have the same effect with instance variables that they have with classes: an instance variable declared public can be accessed both inside and outside of the package in which it is defined; an instance variable declared internal can be accessed inside the package in which it is defined only. The protected and private modifiers are even more restrictive than internal. An instance variable declared protected can be accessed by code in the class that contains the variable's definition, or by code in descendants of that class only (we haven't studied inheritance yet, so if you are new to object-oriented programming, you can simply ignore protected for now). An instance variable declared private can be accessed by code in the class that contains the variable's definition only. When no modifier is specified, internal (package-wide access) is used.

Table 1-2 summarizes the access-control modifiers for instance variables.

Table 1-2. Instance variable access-control modifiers

 

Attribute

Code placement

Public

Internal

Protected

Private

Code in class containing variable's definition

Access allowed

Access allowed

Access allowed

Access allowed

Code in descendant of class containing variable's definition

Access allowed

Access allowed

Access allowed

Access denied

Code in different class in same package as variable's definition

Access allowed

Access allowed

Access denied

Access denied

Code not in same package as variable's definition

Access allowed

Access denied

Access denied

Access denied

By defining a class's instance variables as private, we can keep each instance's information safely encapsulated, preventing other code from relying too heavily on the internal structure of the class or accidentally assigning invalid values to instance variables. In general, it's good form to specify an access-control modifier explicitly for every instance variable. No instance variable should be defined as public unless specifically required by its class's architecture. If you are unsure which access-control modifier to use, use private. Down the road, you can easily make the instance variable more accessible if required. By contrast, if you start with a public instance variable, you'll have a tough time changing it to private later if external code already relies on it.

In the current version of our virtual zoo application, the petName instance variable is used within both the VirtualPet class and the VirtualZoo class, so we should define petName with the access-control modifier internal, as follows:

package zoo {
  internal class VirtualPet {
    internal var petName = "Unnamed Pet";
  }
}

Note that defining an instance variable with the internal attribute is identical to defining the variable with no access-control modifier at all (because internal is the default).

There are plenty more examples of instance variables throughout the remainder of this book. Now let's continue with the development of our virtual zoo program.

So far, the structure of our VirtualPet class requires each VirtualPet object's petName variable to be set voluntarily. If, however, we want to guarantee that a name is supplied for every pet, we can use constructor parameters, as described in the next section.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required