Understanding Encapsulation Using Examples

In this lesson, you will get a firmer understanding of encapsulation in C# with the help of examples.

We'll cover the following

As discussed earlier, encapsulation refers to the concept of binding data and the methods operating on that data in a single unit also called a class.

The goal is to prevent this bound data from any unwanted access by the code outside this class. Let’s continue working with our example of the VendingMachine class to understand the concept of encapsulation.

We know that vending machines collect money from the customers and in return provide them their desired product. This money collection is done with the help of a money collector module installed on the machine. Let’s simulate this module in the form of a class.

A very basic MoneyCollector class’ object should be able to perform the following:

  • Keep track of the total sales.
  • Add the collected money to the total.
  • Provide the change to the user in case the product was of a lesser price than the inserted amount of money.

For the sake of simplicity, we will assume that we have only one product with a fixed price.

Get hands-on with 1200+ tech skills courses.