User Guide
Implicit getter/setter methods 267
Implicit getter/setter methods
Object-oriented programming practice discourages direct access to properties within a class.
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:
var userName:String;
Instead of allowing instances of the class to directly access this property (obj.userName =
"Jody"
, for example), the class might have two methods, getUserName and setUserName, that
would be implemented as shown in the following example:
class LoginClass {
private var userName:String;
function LoginClass(name:String) {
this.userName = name;
}
function getUserName():String {
return this.userName;
}
function setUserName(name:String):Void {
this.userName = name;
}
}
As you can see, getUserName returns the current value of userName, and setUserName sets the
value of
userName to the string parameter passed to the method. An instance of the class would
then use the following syntax to get or set the
userName property:
var obj:LoginClass = new LoginClass("RickyM");
// calling "get" method
var name = obj.getUserName();
trace(name);
// calling "set" method
obj.setUserName("EnriqueI");
trace(obj.getUserName());
However, if you want to use a more concise syntax, use implicit getter/setter methods. Implicit
getter/setter methods let you access class properties in a direct manner, while maintaining good
OOP practice.
To define these methods, use the
get and set method attributes. You create methods that get or
set the value of a property, and add the keyword
get or set before the method name, as shown in
the following example:
class LoginClass2 {
private var userName:String;
function LoginClass2(name:String) {
this.userName = name;
}
function get user():String {