官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 石家庄市| 鹤山市| 塘沽区| 永春县| 盘山县| 阿合奇县| 封开县| 通化县| 离岛区| 邵阳市| 临城县| 南乐县| 凤山市| 济源市| 贺兰县| 康平县| 湘阴县| 河北区| 四子王旗| 涟源市| 库尔勒市| 射阳县| 栖霞市| 大竹县| 股票| 宝山区| 五莲县| 田阳县| 布拖县| 遵义县| 兴义市| 泸州市| 棋牌| 高平市| 阳城县| 南部县| 慈利县| 东宁县| 开鲁县| 山东| 南华县|