Remember that data instance variable private and getters are public
Encapsulating Data 205
Encapsulating Data
Encapsulation to the rescue. Encapsulation means we set up the class so only methods in the class with the variables can refer to the instance variables. Callers are required to use these methods. Let’s take a look at our newly encapsulated Swan class:
1: public class Swan {
2: private int numberEggs; // private
3: public int getNumberEggs() { // getter
4: return numberEggs;
5: }
6: public void setNumberEggs(int numberEggs) { // setter
7: if (numberEggs >= 0) // guard condition
8: this.numberEggs = numberEggs;
9: } }Note numberEggs is now private on line 2. This means only code within the class can read or write the value of numberEggs. Since we wrote the class, we know better than to set a negative number of eggs. We added a method on lines 3–5 to read the value, which is called an accessor method or a getter. We also added a method on lines 6–9 to update the value, which is called a mutator method or a setter. The setter has an if statement in this example to prevent setting the instance variable to an invalid value. This guard condition protects the instance variable.
|
|
---|---|
|
|
---|
|
|
---|