|
|
|
Access controlDo you remember about information hiding? In the examples above, everyone could access all the methods and member variables in all objects. For example, it is very easy to lose weight: h->weight -= 10.0;Oh? The hamster only weighed 0.12, and now it weighs minus 9.88? We would like to control the access to the member variable weight, so that other classes cannot touch it. For uses like this, there are a number of access modifiers, which are written before the data type in the definition of a method or member variable. For example, the weight of an animal is represented by the member variable weight, defined as: float weight;By changing that to private float weight;we only allow methods in the same class to access that variable. The following access modifiers exist:
If a class has a constructor (that is, a method called create) it can be a good idea to declare it static. It is not supposed to be called except during the construction of the object, and if it is not static there may be some type incompatibilities in connection with inheritance. |
|||