MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual page 256

Learning actionscript 2.0 in flash
Table of Contents

Advertisement

When you write classes, you are always encouraged to make as many as possible of your
instance variables private and add getter and setter methods accordingly. This is because there
are several times when you may not want to let users change certain variables within your
classes. For example, if you have a private static method that tracks the number of instances
created for a specific class, you don't want a user to modify that counter using code. Only the
constructor statement should increment that variable whenever it's called. In this situation,
you might create a private instance variable and allow a getter method only for the counter
variable, which means users are able to retrieve the current value only by using the getter
method, and they won't be able to set new values using the setter method. Creating a getter
without a setter is a simple way of making certain variables in your class read-only.
Using getter and setter methods
The syntax for getter and setter methods is as follows:
A getter method does not take any parameters and always returns a value.
A setter method always takes a parameter and never returns a value.
Classes typically define getter methods that provide read access and setter methods that
provide write access to a given property. For example, imagine a class that contains a property
called
:
userName
private var userName:String;
Instead of allowing instances of the class to directly access this property (
, for example), the class might have two methods,
"Buster"
, that would be implemented as shown in the next example.
setUserName()
To use getter and setter methods:
1.
Select File > New and then select ActionScript File, and then click OK.
2.
Type the following code into the Script window:
class Login {
private var __username:String;
public function Login(username:String) {
this.__username = username;
}
public function getUserName():String {
return this.__username;
}
public function setUserName(value:String):Void {
this.__username = value;
}
}
256
Classes
user.userName =
and
getUserName()

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?

Subscribe to Our Youtube Channel

This manual is also suitable for:

Flash 8

Table of Contents