Over 10 Million Study Resources Now at Your Fingertips


Download as :
Rating : ⭐⭐⭐⭐⭐
Price : $10.99
Language:EN
Pages: 2

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.

Rule

Example

Getter methods begin with get if the property is not a boolean.

public int getNumEggs() { return numEggs;

The method name must have a prefix of set/get/is, followed by the first
letter of the property in uppercase, fol-lowed by the rest of the property name.

public void setNumEggs(int num) { numEggs = num;
}

How It Works
Login account
Login Your Account
Add to cart
Add to Cart
Payment
Make payment
Document download
Download File
PageId: ELIA4192CB
img
Uploaded by :
qQNnqPKo
Page 1 Preview
remember that data instance variable private and g
Sell Your Old Documents & Earn Wallet Balance