- Hands-On Object:Oriented Programming with C#
- Raihan Taher
- 275字
- 2021-07-02 12:44:42
Encapsulation
Encapsulation means hiding or covering. In C#, encapsulation is achieved by access modifiers. The access modifiers that are available in C# are the following:
- Public
- Private
- Protected
- Internal
- Internal protected
Encapsulation is when you want to control other classes' access to a certain class. Let's say you have a BankAccount class. For security reasons, it isn't a good idea to make that class accessible to all classes. It's better to make it Private or use another kind of access specifier.
You can also limit access to the properties and variables of a class. For example, you might need to keep the BankAccount class public for some reason, but make the AccountBalance property private so that no other class can access this property except the BankAccount class. You can do this as follows:
public class BankAccount {
private double AccountBalance { get; set; }
}
Like variables and properties, you can also use access specifiers for methods. You can write private methods that are not needed by other classes, or that you don't want to expose to other classes. Let's look at the following example:
public class BankAccount{
private double AccountBalance { get; set; }
private double TaxRate { get; set; }
public double GetAccountBalance() {
double balanceAfterTax = GetBalanceAfterTax();
return balanceAfterTax;
}
private double GetBalanceAfterTax(){
return AccountBalance * TaxRate;
}
}
In the preceding example, the GetBalanceAfterTax method is a method that will not be needed by other classes. We only want to provide the AccountBalance after tax, so we can make this method private.
Encapsulation is a very important part of OOP as it gives us control over code.
- Unreal Engine Physics Essentials
- Implementing Modern DevOps
- Microsoft Dynamics 365 Extensions Cookbook
- 你必須知道的204個Visual C++開發(fā)問題
- Banana Pi Cookbook
- Python數據挖掘與機器學習實戰(zhàn)
- Python時間序列預測
- 劍指Java:核心原理與應用實踐
- C#開發(fā)案例精粹
- C++程序設計
- Mastering PowerCLI
- INSTANT PLC Programming with RSLogix 5000
- Java EE基礎實用教程
- Python程序設計:基礎與實踐
- Python數據分析與挖掘實戰(zhàn)(第2版)