Getters and setters are methods that are behaved like properties. it means they have function structure but when used, they are used same as properties:
Structure of getter functions:
they should have get
keyword after function
keyword and before function name, with no argument, a return type specified and must return a value:
public function get myValue():Type{
//anything here
return _desiredValue;
}
Syntax:
to get the value from a getter,the syntax is the same as getting a value from a property(no parens ()
are used).
trace(myValue);
Structure of setter functions:
they should have set
keyword after function
keyword and before function name, with one argument, and no value return.
public function set myValue(value:Type):void{
//anything here
_desiredProperty=value;
}
Syntax:
to set the value of a setter,the syntax is the same as setting a value to a property(using equal sign =
then value).
myValue=desiredValue;
setting a getter and setter for one value:
Note: if you create only getter or only setter with a name, that property would be read-only or set-only.
to make a property both readable and setable, should create a getter and a setter with:
1.the same name.
2.the same type(type of return value for the getter and type of input value(argument) for the setter,
Note: getters and setters should not have a name same as other properties or methods .
Usage of getters and setters:
Using getters and setters rather than normal properties has many pros:
1.making read-only or set-only properties:
for example number of children in a display object. it can't be setable.
2.accessing private properties:
an example:
private var _private:Type=new Type();
//note that function name "private" is not same as variable name "_private"
public function get private():Type{
return _private;
}
3.when some change is required after setting a value:
in this example, changing this property must be notified:
public static function set val:(input:Type):void{
_desiredProperty=input;
notifyValueChanged();
}
and many other usages