On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Problem
  4. 2. Private Members: Start the Name With _
  5. 3. Privacy Is Per File
  6. 4. The Pattern
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 046: Encapsulation

DayExtra Topics
Lecture046 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

A bank doesn't let you walk into the vault and change your balance. You use the counter, and the counter checks every request. Encapsulation does the same for objects: the data is hidden, and outside code can only change it through methods that check the rules.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 030–035: classes, constructors, getters and setters.


Learning Objectives

  • Explain encapsulation and why it protects data
  • Make a field private with _
  • Know that Dart privacy works per file, not per class
  • Give read-only access with a getter
  • Check values in methods and setters before saving them

1. The Problem

dart
class BankAccount {
  double balance = 0;
}

var account = BankAccount();
account.balance = -5000;   // nothing stops this!

Any code anywhere can put nonsense into balance. Encapsulation fixes that.

2. Private Members: Start the Name With _

In Dart, a name that starts with an underscore (_balance) is private: only code in the same file can see it. Put the class in its own file:

bank_account.dart

dart
class BankAccount {
  final String owner;
  double _balance;          // private: only code in this file can touch it

  BankAccount(this.owner, this._balance);

  double get balance => _balance;   // read-only from outside

  void deposit(double amount) {
    if (amount <= 0) {
      print('Deposit must be positive.');
      return;
    }
    _balance += amount;
    print('Deposited $amount. Balance: $_balance');
  }

  void withdraw(double amount) {
    if (amount > _balance) {
      print('Not enough money. Balance: $_balance');
      return;
    }
    _balance -= amount;
    print('Withdrew $amount. Balance: $_balance');
  }
}

main.dart

dart
import 'bank_account.dart';

void main() {
  var account = BankAccount('Hamza', 1000);
  account.deposit(500);
  account.withdraw(2000);
  account.withdraw(300);
  print(account.balance);
  print(account.owner);
}

Output

code
Deposited 500.0. Balance: 1500.0
Not enough money. Balance: 1500.0
Withdrew 300.0. Balance: 1200.0
1200.0
Hamza

main.dart can read balance through the getter, but the only way to change it is through deposit and withdraw, which check the rules.

3. Privacy Is Per File

Dart has no private keyword. The _ rule applies to the whole file (Dart calls it a library). Two classes in the same file can see each other's _ members. That's why the examples here put the class in its own file. If everything is in one file, _ hides nothing from main.

4. The Pattern

  1. Make the field private (_balance).
  2. Add a getter if outside code should read it.
  3. Add methods or a setter that validate before changing it.

Code Examples

Example 1: Marks That Must Stay Between 0 and 100

student.dart

dart
class Student {
  final String name;
  int _marks = 0;

  Student(this.name);

  int get marks => _marks;

  set marks(int value) {
    if (value < 0 || value > 100) {
      print('Invalid marks: $value (must be 0–100)');
      return;
    }
    _marks = value;
  }

  String get grade {
    if (_marks >= 80) return 'A';
    if (_marks >= 60) return 'B';
    if (_marks >= 40) return 'C';
    return 'F';
  }
}

main.dart

dart
import 'student.dart';

void main() {
  var s = Student('Zara');
  s.marks = 87;
  print('${s.name}: ${s.marks} → ${s.grade}');
  s.marks = 140;
  print('${s.name}: ${s.marks} → ${s.grade}');
  s.marks = 55;
  print('${s.name}: ${s.marks} → ${s.grade}');
}

Output

code
Zara: 87 → A
Invalid marks: 140 (must be 0–100)
Zara: 87 → A
Zara: 55 → C

s.marks = 140 looks like a normal assignment, but it runs the setter, which refuses the bad value. grade is calculated from _marks, so it can never be out of date.


Common Beginner Mistakes

1. Touching a private field from another file

dart
account._balance = 1000000;
code
Error: The setter '_balance' isn't defined for the type 'BankAccount'.

That's encapsulation working. Use deposit().

2. Assigning to a getter-only property

dart
account.balance = 5;
code
Error: The setter 'balance' isn't defined for the type 'BankAccount'.

balance has a getter but no setter, so it's read-only.

3. Testing privacy in one file: if the class and main are in the same file, _balance is visible to main and you'll think privacy is broken. Move the class to its own file.

4. A getter and setter that check nothing: int get x => _x; set x(v) => _x = v; adds code but no protection. Validate in the setter, or just use a public field.


Practice Questions

  1. How do you make a field private in Dart?
  2. Is _name hidden from another class in the same file?
  3. How do you let other files read a private field but not change it?
  4. Why is account.withdraw(300) safer than account.balance -= 300?
  5. Write a setter for _age that refuses negative numbers.

Practice Answers

  1. Start its name with _.
  2. No. Privacy is per file, so classes in the same file can see it.
  3. Add a getter (int get age => _age;) and no setter.
  4. withdraw can check that there's enough money first; direct changes skip every check.
dart
set age(int value) {
  if (value < 0) {
    print("Age can't be negative");
    return;
  }
  _age = value;
}

Key Takeaways

  • Encapsulation = hide the data, allow changes only through checked methods.
  • A leading _ makes a member private to its file.
  • Getter without a setter = read-only from outside.
  • Validate in setters and methods so objects never hold bad values.