Encapsulation is the ability to contain and control access to a group of associated items. Classes provide one of the most common ways to encapsulate items. In the example below, the BankAccount class encapsulates the methods, fields, and properties that describe a bank account.
Without encapsulation, you would declare separate procedures and variables to store and manage information for the bank account, and it would be difficult for you to work with more than one bank account at a time. With encapsulation you can use the data and procedures in the BankAccount class as a unit. You can work with multiple bank accounts at the same time without confusion because each account is represented by a unique instance of the class.
Encapsulation also allows you to control how the data and procedures are used. You can use access modifiers, such as Private or Protected, to prevent outside procedures from executing class methods or reading and modifying data in properties and fields. You should declare internal details of a class as Private to prevent them from being used outside of your class; this technique is called data hiding, and is how customer information such as the account balance is protected.
One basic rule of encapsulation is that class data should be modified or retrieved only via Property procedures or methods. Hiding the implementation details of your classes prevents classes from being used in undesired ways, and lets you to later modify such items without risk of compatibility problems. For example, later versions of the BankAccount class could change the data type of the AccountBalance field without breaking other applications that rely on this field having a specific data type.