About working with custom classes in an application 251
Similarly, any function declared within a class is considered a method of the class. In the
Person class example, you can create a method called
getInfo():
class Person {
public var age:Number;
public var username:String;
public function getInfo():String {
// getInfo() method definition
}
}
In the previous code snippet the Person class’s getInfo() method, as well as the age and
username properties, are all public instance members. The age property would not be a good
class member, because each person has a different age. Only properties and methods that are
shared by all individuals of the class should be class members.
Suppose that you want every class to have a
species variable that indicates the proper Latin
name for the species that the class represents. For every Person object, the species is Homo
sapiens. It would be wasteful to store a unique copy of the string
"Homo sapiens" for every
instance of the class, so this member should be a class member.
Class members are declared with the
static keyword. For example, you could declare the
species class member with the following code:
class Person {
public static var species:String = "Homo sapiens";
// ...
}
You can also declare methods of a class to be static, as shown in the following code:
public static function getSpecies():String {
return Person.species;
}
Static methods can access only static properties, not instance properties. For example, the
following code results in a compiler error because the class method
getAge() references the
instance variable
age:
class Person {
public var age:Number = 15;
// ...
public static function getAge():Number {
return age; /* **Error**: Instance variables cannot be accessed in
static functions. */
}
}
To solve this problem, you could either make the method an instance method or make the
variable a class variable.