- 1
I am having difficulty understanding the Encapsulation lesson, is there anyone who can explain the solution to me step by step
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class BankAccount { private double balance=0; public void Deposit(double n) { balance += n; } public void Withdraw(double n) { balance -= n; } public double GetBalance() { return balance; } } class Program { static void Main(string[] args) { BankAccount b = new BankAccount(); b.Deposit(199); b.Withdraw(42); Console.WriteLine(b.GetBalance()); } } }
2 Respuestas
+ 5
By simple terms:-
1) We will have the class variables declared as private.
2) To access those variables (modify/get value) outside that class, we will have getters and setters methods.
In your example withdraw() & deposit() acts as setters and getBalance() acts as getter.
The reason behind this kind of approach is to prevent accessing the value of the variable directly like BankAccount.balance = 100.
Think of this situation,
you should only be able to modify your bank balance only when you either deposit and withdraw and should prevent modifying balance like BankAccount.balance = 100.
To achieve this encapsulation is used.
0
Niththish
I don't understand what this example has to do with encapsulation? This example is a class with attributes and functions and I don't know what difference Public and Private will make