Writing custom class files 237
The User class’s constructor statement takes two parameters: p_username and
p_password, which are copied into the class’s private instance variables __username and
__password. The remainder of the code in the class defines the getter and setter
properties for the private instance variables. If you want to create a read-only property,
then you would define a getter function, but not a setter function. For example, if you
want to make sure a user name cannot be changed after it has been defined, you would
delete the
username setter function in the User class file.
5. Select File > New and then select Flash Document.
6. Select File > Save As and name the file user_test.fla. Save the file in the same directory as
User.as.
7. Type the following ActionScript into Frame 1 of the Timeline:
import User;
var user1:User = new User("un1", "pw1");
trace("Before:");
trace("\t username = " + user1.username); // un1
trace("\t password = " + user1.password); // pw1
user1.username = "1nu";
user1.password = "1wp";
trace("After:");
trace("\t username = " + user1.username); // 1nu
trace("\t password = " + user1.password); // 1wp
Because the User class you created previously is very basic, the ActionScript in the Flash
document is also very straightforward. The first line of code imports the custom User class
into your Flash document. Importing the User class lets you use the class as a custom data
type.
A single instance of the User class is defined and assigned to a variable named
user1. You
assign the
user1 User object a value and define a username of un1 and a password of
pw1. The following two trace statements display the current value of user1.username
and
user1.password using the User class’s getter functions, which both return strings.
The next two lines use the User class’s setter functions to set new values for the
username
and
password variables. Finally, you trace the values for username and password to the
Output panel. The
trace statements display the modified values that you set using the
setter functions.
8. Save the FLA file, and then select Control > Test Movie to test the files.
You see the results of the trace statements in the Output panel. In the next examples,
you use these files in an application.