Thursday, January 24, 2019

We Will Now Look At Those In Greater Detail

Now we have a method in the ‘Orders’ class, which is used to display the order ID and description. There are many more aspects to object oriented programming and uses for classes. We will now look at those in greater detail.

22.1 Encapsulation

This refers to the encapsulation or bundling of data and methods into classes. An integral part of this mechanism is the visibility of this data in the class. There are situations where we don’t want to directly allow other code to access the data defined in the class. In such cases, we only want data to be accessed via methods defined in the class. There are different levels of visibility which are defined by class modifiers. There are:

  • Private – With private, the properties and methods are only available to the class itself.
  • Protected - With protected, the properties and methods are available to the class itself and subclasses derived from that class.
  • Public - With public, the properties and methods are available to all classes.

An example of how data can be encapsulated in a C# class is shown below. In this code we define the student ID and the student Name as private members so that they cannot be accessed directly. If any other code wants to see the ID and name values, they can call the ‘Display’ method of the class.