OOP in Dart with Person, Currency & BankAccount 💳
In this blog, we’ll explore Dart OOP using three classes:
Person, Currency, and BankAccount.
We’ll explain constructors, toString()
, static vs instance members, and also use UML diagrams to visualize relationships.
Complete Code
OOP Example in Dart: Person, Currency, and BankAccount
class Person {
String name;
int age;
// Constructor
Person(this.name, this.age);
// toString method
@override
String toString() {
return "Person(name: $name, age: $age)";
}
}
class Currency {
int totalPaisa;
// Constructor using rupees and paisa
Currency({int rupees = 0, int paisa = 0})
: totalPaisa = rupees * 100 + paisa;
// Add two currencies
Currency operator +(Currency other) {
return Currency(paisa: this.totalPaisa + other.totalPaisa);
}
// Show rupees and paisa properly
@override
String toString() {
int rupees = totalPaisa ~/ 100;
int paisa = totalPaisa % 100;
return "₹${rupees}.${paisa.toString().padLeft(2, '0')}";
}
}
class BankAccount {
static int accountCounter = 1000;
int accountNumber;
Person owner;
Currency balance;
// Constructor
BankAccount(this.owner, this.balance)
: accountNumber = ++accountCounter;
// Deposit money
void deposit(Currency amount) {
balance = balance + amount;
}
// toString
@override
String toString() {
return "BankAccount(accountNo: $accountNumber, owner: ${owner.name}, balance: $balance)";
}
}
void main() {
Person p1 = Person("Shubham", 22);
Currency initial = Currency(rupees: 500, paisa: 50);
BankAccount acc = BankAccount(p1, initial);
print(acc);
acc.deposit(Currency(rupees: 200, paisa: 75));
print("After deposit: $acc");
}
class Person { String name; int age; Person(this.name, this.age); @override String toString() { return "Person(name: $name, age: $age)"; } }
2. Currency Class 💰
class Currency { double amount; String code; static int totalCurrencies = 0; Currency(this.amount, this.code) { totalCurrencies++; } @override String toString() { return "$amount $code"; } }
3. BankAccount Class 🏦
class BankAccount { Person owner; Currency balance; static int totalAccounts = 0; BankAccount(this.owner, this.balance) { totalAccounts++; } void deposit(double amt) { ... } void withdraw(double amt) { ... } @override String toString() { return "BankAccount(owner: $owner, balance: $balance)"; } }
4. Relationship Diagram 📊
👉 The BankAccount
class has-a relationship with both Person
and Currency
.
This is called association in UML.
5. Assignments 📝
- Modify
Currency
to addconvert()
from INR to USD. - Add a
transfer()
method inBankAccount
. - Add a
static bankInfo()
inBankAccount
. - Create
VIPAccount
extendingBankAccount
withloan()
. - Override
toString()
inVIPAccount
to prepend[VIP]
.
0 Comments