We discussed access modifiers in Chapter 7. The purpose of an access modifier is the same for variables as it is for classes. An access modifier applied to a variable defines how the variable can be accessed outside of the class in which it is defined. There are four types of access applicable to a variable: public , protected , private , and default.
The access types and ramifications are summarized in Table 8.2. Note that variables are always available inside the class in which they are defined regardless of their access modifiers. It is only for access outside of the variable's class that access modifiers come into play. It is generally considered bad form to declare instance variables as public . By doing so you lose some control over your class. Someone who uses the class for another application might do things with your data members that you never intended, such as change the value of a variable that was intended to be read-only. Or someone could inadvertently set a length or weight to be negative. Table 8.2. Variable Accessibility
The proper way to access variables outside the class in which they are defined is by using methods. The methods can make sure that the variables are not set to inappropriate values. This goes back to satisfying the object-oriented concept of encapsulation. |