Question #72EasyDart Basics

What is Object Oriented Programming in Dart: Encapsulation ?

#dart

Answer

Overview

Encapsulation is the OOP principle of bundling data (fields) and behavior (methods) within a class, and restricting direct access to internal data from outside the class.


Encapsulation in Dart

In Dart, privacy is achieved with the

text
_
prefix (library-private):

dart
class BankAccount {
  // Private fields — hidden from outside
  final String _accountId;
  double _balance;

  // Constructor — controlled initialization
  BankAccount(this._accountId, double initialBalance)
      : _balance = initialBalance >= 0 ? initialBalance : 0;

  // Public getters — read-only access
  String get accountId => _accountId;
  double get balance => _balance;

  // Public methods — controlled modification
  bool deposit(double amount) {
    if (amount <= 0) return false;
    _balance += amount;
    print('Deposited: ₹$amount | New balance: ₹$_balance');
    return true;
  }

  bool withdraw(double amount) {
    if (amount <= 0 || amount > _balance) {
      print('Invalid withdrawal');
      return false;
    }
    _balance -= amount;
    return true;
  }

  // Private helper — only used internally
  bool _isValidAmount(double amount) => amount > 0;
}

void main() {
  final account = BankAccount('ACC001', 1000);

  print(account.balance);  // ✅ 1000.0 — via getter
  account.deposit(500);    // ✅ Controlled access
  account.withdraw(200);   // ✅ Controlled access

  // account._balance = 999999; // ❌ Error — private in another file
  // account.balance = 0;       // ❌ No setter — read only
}

Getter and Setter

dart
class Temperature {
  double _celsius;

  Temperature(this._celsius);

  // Getter
  double get celsius => _celsius;
  double get fahrenheit => _celsius * 9/5 + 32;
  double get kelvin => _celsius + 273.15;

  // Setter with validation
  set celsius(double value) {
    if (value < -273.15) throw ArgumentError('Below absolute zero!');
    _celsius = value;
  }
}

final temp = Temperature(25);
print(temp.fahrenheit); // 77.0
temp.celsius = 100;     // Uses setter

Benefits of Encapsulation

BenefitExample
ValidationPrevent negative balance
Read-only accessExpose getter, no setter
Internal changesChange
text
_balance
type without breaking API
DebuggingLog/audit inside setter
SecurityHide sensitive data

Rule: Make all fields private (

text
_name
). Expose data through getters. Allow changes only through controlled methods. This maintains control over your class's internal state.