Conteúdo do Curso
C# Beyond Basics
C# Beyond Basics
Encapsulation
Encapsulation is essentially just a method of data organization. It involves organizing data and methods in the forms of classes so the whole program is essentially just based around classes and the data and methods are encapsulated within those classes. This encapsulation provides a way to control access to the internal state of an object, promoting modularity, maintainability, and security in a software system.
In Encapsulation, we use the Access Modifiers like public
, private
and protected
to hide all most of the fields and methods of a class and expose only the ones that are needed to be used from outside.
Since most of the data is directly inaccessible outside the class, we use getters and setters to access or modify the data.
One good example is a Customer
class which defines the customer of a bank:
index
public class Customer { private double accountBalance; private string customerName; private int pinCode; public Customer(double accountBalance, string customerName, int pinCode) { this.accountBalance = accountBalance; this.customerName = customerName; this.pinCode = pinCode; } public double getBalance(int pinCode) { if (pinCode == this.pinCode) return this.accountBalance; return } public void Deposit(double amount, int pinCode) { if(pinCode == this.pinCode) accountBalance += amount; } public void Withdraw(double amount, int pinCode) { if(pinCode == this.pinCode) accountBalance -= amount; } }
In the above example, no field is directly accessible or modifiable from outside. Instead we use methods like Deposit
and Withdraw
to modify the value whenever needed. Similarly to access the value of the balance we use the getBalance
method.
The public
keyword is generally discouraged to be used unless necessary.
Obrigado pelo seu feedback!