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.
class BankAccountPublic
{
// Access at all levels
public decimal GetAmount()
{
return 1000.00m;
}
}
Note: The GetAmount()
function is available to all classes
public class BankAccountPrivate
{
//Customary to put an _ before private fields.
private string _name;
private int _accountNumber;
public string CustomerName
{
get { return _name; }
set { _name = value; }
}
}
Note ApplyLateCharges()
and CalculateInterest()
are available to BankAccountProtected
class and derived classes (BankAccountReopenedClosedAccount) because of the protected
modifier.
public class BankAccountProtected
{
// Available to current and derived classes
public void CloseAccount()
{
ApplyLateCharges();
CalculateInterest();
}
// Available to current and derived classes
protected virtual void ApplyLateCharges()
{
Console.WriteLine("Apply Late Charges ran.");
}
protected virtual void CalculateInterest()
{
Console.WriteLine("Calculate Interest ran.");
}
}
public class BankAccountReopenClosedAccount : BankAccountProtected
{
public void SettleDebt()
{
ApplyLateCharges();
CalculateInterest();
}
}
Next: Getters and Setters
Last updated