Tài liệu Getters and Setters - Pdf 87


< Day Day Up >

Getters and Setters
As you're well aware by now, when you create an instance of a class you're actually
creating an object. Often these objects have properties, as defined by their class files. For
example, look at this class definition:

class State {

var population:Number;

function State() {

//Constructor

}

} This defines the State class. This class has a single property named population, which is
obviously used to hold the number of people in the state.
Creating an instance of this class would look like this:

var northCarolina:State = new State();
function setPopulation(num:Number){

population = num + (num * .05);

}

function getPopulation():Number{

return population;

}

} As defined by the class now, setting and getting the population property are handled by
methods, which can be used in the following way:

northCarolina.setPopulation(8000000); //automatically adds a 5% growth rate when set

northCarolina.getPopulation(); // returns a value of 8400000 Either of these getter or setter methods could be changed or enhanced as needed from
within the class definition. As a result, all scripts in all projects that use the State class
would automatically reflect the new functionality.
Because of the versatility of getters and setters, getting and setting property values
directly is considered bad coding practice. Set up and use getter and setter methods
instead.
Implicit get and set Methods

methods have been changed to set population and get population, respectively. This
change converts the methods to what are known as implicit get and set methods. What
does this mean? You get the best of both worlds—property values can be set or retrieved
within the class file by using functions, but referencing them in a script is as easy as this:

northCarolina.population = 8000000; or this:

var myVariable:Number = northCarolina.population; With this syntax, it seems as if we're once again referencing the population property
directly, but we're actually calling either the set population or get population method
(depending on the task) to take care of the state's population. Notice that we changed the
name of the population property to statePopulation. If we hadn't done this, using the
following syntax:

northCarolina.population = 8000000; would result in an error. Flash wouldn't know if we were attempting to set the property
named population or invoking the set population set method, because doing either
requires the same syntax. Changing the population property name to statePopulation
solves this problem.
NOTE
Using implicit get and set methods offers no technical advantages over using the getter
and setter methods described in the previous section, other than saving a few keystrokes.


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status