162 Chapter 9: Creating Classes with ActionScript 2.0
Similarly, any function declared within a class is considered a method of the class. In the Person
class example, you created a single method called
showInfo().
class Person {
var age:Number;
var name:String;
function showInfo() {
// showInfo() method definition
}
}
Initializing properties inline
You can initialize properties inline—that is, when you declare them—with default values, as
shown here:
class Person {
var age:Number = 50;
var name:String = "John Doe";
}
When you initialize properties inline the expression on the right side of an assignment must be a
compile-time constant. That is, the expression cannot refer to anything that is set or defined at
runtime. Compile-time constants include string literals, numbers, Boolean values,
null, and
undefined, as well as constructor functions for the following built-in classes: Array, Boolean,
Number, Object, and String.
For example, the following class definition initializes several properties inline:
class CompileTimeTest {
var foo:String = "my foo"; // OK
var bar:Number = 5; // OK
var bool:Boolean = true; // OK
var name:String = new String("Jane"); // OK
var who:String = foo; // OK, because 'foo' is a constant
var whee:String = myFunc(); // error! not compile-time constant expression
var lala:Number = whee; // error! not compile-time constant expression
var star:Number = bar + 25; // OK, both 'bar' and '25' are constants
function myFunc() {
return "Hello world";
}
}
This rule only applies to instance variables (variables that are copied into each instance of a class),
not class variables (variables that belong to the class itself). For more information about these
kinds of variables, see “Instance and class members” on page 165.
Creating subclasses
In object-oriented programming, a subclass can inherit the properties and methods of another
class, called the superclass. To create this kind of relationship between two classes, you use the
class statement’s extends clause. To specify a superclass, use the following syntax:
class SubClass extends SuperClass {}