Chapter 3. Instance Methods Revisited
In Chapter 1, we learned how to create instance methods. In this chapter, we’ll expand that basic knowledge by studying the following additional instance-method topics:
Omitting the
thiskeywordBound methods
State-retrieval and state-modification methods
Get and set methods
Extra arguments
Along the way, we’ll continue developing the virtual zoo program that we started in Chapter 1. But before we begin, take a minute to reacquaint yourself with the virtual zoo program. Example 1 shows the code as we last saw it.
// VirtualPet class
package zoo {
internal class VirtualPet {
internal var petName;
private var currentCalories = 1000;
private var creationTime;
public function VirtualPet (name) {
this.creationTime = new Date();
this.petName = name;
}
public function eat (numberOfCalories) {
this.currentCalories += numberOfCalories;
}
public function getAge () {
var currentTime = new Date();
var age = currentTime.time - this.creationTime.time;
return age;
}
}
}
// VirtualZoo class
package zoo {
public class VirtualZoo {
private var pet;
public function VirtualZoo () {
this.pet = new VirtualPet("Stan");
}
}
}Omitting the this Keyword
In Chapter 1, we learned that the
this keyword is used to refer to
the current object within constructor methods and instance methods.
For example, in the following code, the expression this.petName = name tells ActionScript to
set the value of the instance variable petName on the object currently being created: ...