Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Earlier, we learned that a local variable expires when the method or function in which it is defined finishes executing. To make sure that the VirtualPet instance in our VirtualZoo class will be accessible after the VirtualZoo constructor finishes, let's update the VirtualZoo class. Instead of assigning our VirtualPet object to a local variable, we'll assign it to an instance variable, pet. We'll make pet private so that it can be accessed by code in the VirtualZoo class only. Here's the code (the new instance variable is shown in bold):
package zoo {
public class VirtualZoo {
private var pet;
public function VirtualZoo () {
this.pet = new VirtualPet("Stan");
}
}
}