Earlier we learned that it's good object-oriented practice to declare instance variables private, meaning that they cannot be read or modified by code outside of the class in which they are defined. Good object-oriented practice dictates that, rather than allow external code to modify instance variables directly, we should instead define instance methods for examining or changing an object's state.
For example, earlier, we gave our VirtualPet class an instance variable named
currentCalories variable conceptually
describes the state of each pet's hunger. To allow external code to
reduce the pet's hunger level, we could make
accessible. External code could then set the pet's hunger state to any
arbitrary value, as shown in the following code:
somePet.currentCalories = 5000;
The preceding approach, however, is flawed. If external code can
then the VirtualPet class has no
way to ensure that the value assigned to that variable is legal, or
sensible. For example, external code might assign
currentCalories 1000000, causing the pet to
live for hundreds of years without getting hungry. Or external code
negative value, which might cause the program to malfunction.
To prevent these problems, we should declare
currentCalories as private (as we did
earlier in our VirtualPet class).
Rather than allowing external code to modify