Dart
Summary - Encapsulation
Combine private, getter/setter and static to write an Account class.
Summary - Encapsulation
In this group you saw the basic tools of encapsulation: private, getter/setter, final/const, late and static. Now we will merge them in an Account class.
An Account class will hold a private _balance field and offer controlled access through a getter and setter. It will also count every new account via a static int totalAccounts counter. Combining the two gives instance level privacy and class level sharing, a complete example of encapsulation.
Exercise Add a private field and accessors to Account
Define a class named Account. Add a private double _balance field. Write an Account(double initial) : _balance = initial; constructor. Add a double get balance => _balance; getter and a set balance(double value) { if (value < 0) return; _balance = value; } setter. In main, create an instance with var a = Account(100); and call print(a.balance).
Show example solution
// Define the Account class
class Account {
double _balance;
Account(double initial) : _balance = initial;
double get balance => _balance;
set balance(double value) {
if (value < 0) return;
_balance = value;
}
}
void main() {
var a = Account(100);
print(a.balance);
}
Add a static counter to Account
In the second step we add a static counter to the Account class. This counter tracks at class level how many Account instances have been created.
Example: a static int totalAccounts = 0; field and totalAccounts++; inside the constructor. Each new Account instance increments the counter. Read it via Account.totalAccounts on the class; no instance is needed. This shape fits collecting statistics, tracking resources and numbering instances uniquely.
Exercise Add a static counter to Account
Keep the existing Account class (private _balance, constructor, getter, setter). Add a static int totalAccounts = 0; field to the class. Add a totalAccounts++; statement to the constructor body (open a constructor body after the _balance = initial initializer list). In main, create two instances with var a = Account(100); and var b = Account(200);, then call print(Account.totalAccounts) and print(a.balance).
Show example solution
class Account {
double _balance;
static int totalAccounts = 0;
Account(double initial) : _balance = initial {
totalAccounts++;
}
double get balance => _balance;
set balance(double value) {
if (value < 0) return;
_balance = value;
}
}
void main() {
var a = Account(100);
var b = Account(200);
print(Account.totalAccounts);
print(a.balance);
}
Test yourself
-
Which is true for an Account class?
- balance must be static
- _balance is public, no balance method exists
- _balance is private, balance is reached through getter/setter
- _balance must be marked late
Show answer
_balance is private, balance is reached through getter/setter — A private field plus accessors is the core of encapsulation.
Next lesson: mixin