5.2 Encapsulation
File Location
Right click on your solution
Go to Add > New Project and select Class Library
Name it
Encapsulation
Discussion
Encapsulation, in the context of C#, refers to an object's ability to hide data and behaviors that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object. (techopedia.com)
Encapsulation, in object oriented programming, prevents access to implementation details.
We learned about access modifiers in Part 3 of the modules. Encapsulation is basically the implementation of those access modifiers. Making elements of the program public
, private
, protected
, internal
, and protected internal
.
Keyword
Applicable To
Meaning
public
Class, Member
No restrictions
protected
Member
Access limited to the class and derived class
private
Member
Access limited to the class
internal
Class, Member
Access limited to the current assembly
protected internal
Member
Access limited to the current assembly and derived types
For example, the public access modifier allows access to any code, but the private access modifier restricts access to only members of a type. Other access modifiers restrict access in the range somewhere between public and private. While you can use any of the access modifiers on type members, the only two access modifiers you can use on types are public
and internal
.
You can read more on this topic here.
Here is a bank example of why encapsulation could be useful.
Note: The GetAmount()
function is available to all classes
Note ApplyLateCharges()
and CalculateInterest()
are available to BankAccountProtected
class and derived classes (BankAccountReopenedClosedAccount) because of the protected
modifier.
Next: Getters and Setters
Last updated