Understanding encapsulation

Encapsulation basically involves grouping all the related properties and methods that access them in an object. Whenever an application is being designed, we need to decide how many objects should be defined in it, along with the associated attributes and methods available in it. 

For instance, in the car example, we have the following associated attributes and methods:

  • car is an object.
  • The make, model, and color are the different attributes that are present in the object.
  • start, stop, and accelerate are the different methods that are present in the object.

Encapsulation allows us to achieve the following functionality in any application:

  • Security: Using encapsulation, we can define our attributes in such a way that not all of the attributes of an object are exposed to the entire application. In Chapter 2Understanding Classes, Structures, and Interfaces, we used access modifiers to control the security access of any property/method in the class/in the namespace/in the assembly, as well as in the entire application. 
  • Code maintenance: From a maintenance perspective of a function, it's always desirable that the function has as few attributes as possible. 

Using encapsulation, we can organize the required parameters of a function as an attribute of the class and thus we are not passing them explicitly in every call. 

In the following code example, we will go through a code sample in C# and understand how this can be achieved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.29