On this page11 sections
Lecture 046: Encapsulation
| Day | Extra Topics |
| Lecture | 046 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
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
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
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
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
Deposited 500.0. Balance: 1500.0
Not enough money. Balance: 1500.0
Withdrew 300.0. Balance: 1200.0
1200.0
Hamzamain.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
- Make the field private (
_balance). - Add a getter if outside code should read it.
- Add methods or a setter that validate before changing it.
Code Examples
Example 1: Marks That Must Stay Between 0 and 100
student.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
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
Zara: 87 → A
Invalid marks: 140 (must be 0–100)
Zara: 87 → A
Zara: 55 → Cs.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
account._balance = 1000000;Error: The setter '_balance' isn't defined for the type 'BankAccount'.That's encapsulation working. Use deposit().
2. Assigning to a getter-only property
account.balance = 5;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
- How do you make a field private in Dart?
- Is
_namehidden from another class in the same file? - How do you let other files read a private field but not change it?
- Why is
account.withdraw(300)safer thanaccount.balance -= 300? - Write a setter for
_agethat refuses negative numbers.
Practice Answers
- Start its name with
_. - No. Privacy is per file, so classes in the same file can see it.
- Add a getter (
int get age => _age;) and no setter. withdrawcan check that there's enough money first; direct changes skip every check.
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.