Encapsulation

Encapsulation enables you to control the access to data within a class. For example, suppose your class has a number of methods that work on some data. Code that calls into the instantiated class (the object) need not know how a particular operation functions. To perform an action, the calling code need know only that the functionality exists and that it needs to call it. By not allowing direct external access to those methods and by hiding the logic used in the class, you are following the principle of encapsulation.

You can hide the implementation of your class by using access modifiers that prevent code outside the class from modifying data within the class or calling its methods. For example, you can use the Private keyword with a property or method that you don't want outside code to access. However, if you want to manipulate data from outside the class, you must provide public properties or methods. This was illustrated in the Sentence class you created earlier in this chapter. The Text property of the Sentence class had a Get property procedure and a Set property procedure that enabled you to write code to assign values to and retrieve values from the property. The actual data, however, was stored in a private member variable that was not directly accessible from outside the class.

The value of this feature becomes clearer if we add logic along with setting the internal value, such as checking the spelling of the sentence. The developer who sets the text property doesn't have to know how the Sentence object is checking the spelling, only that it does check the spelling when it sets the value.

0 0

Post a comment