Professional Documents
Culture Documents
Encapsulation
Encapsulation
void _privateMethod() {
// Private method
}
void publicMethod() {
// Public method
}
}
3. Benefits of Encapsulation
- Data Hiding: Internal details of an object are hidden from the outside world, providing
a clear and manageable interface for interacting with the object.
Dart(OOP) Page 1
String get name => _name; // Getter
5. Encapsulation Example:
class BankAccount {
String _accountNumber; // Private field
double _balance; // Private field
double getBalance() {
return _balance;
}
}
void main() {
var account = BankAccount('123456', 1000.0);
account.deposit(500.0);
print('Balance after deposit: ${account.getBalance()}'); //
Output: Balance after deposit: 1500.0
account.withdraw(200.0);
print('Balance after withdrawal: ${account.getBalance()}'); //
Output: Balance after withdrawal: 1300.0
}
In this example:
- `BankAccount` class encapsulates `_accountNumber` and `_balance` fields with
methods `deposit()` and `withdraw()` controlling access to `_balance`.
- The `_balance` is accessed and updated through methods, ensuring proper
encapsulation and data integrity.
Dart(OOP) Page 2