Dart Object-Oriented Programming
Understanding OOP concepts in Dart programming
🎯 What is Dart OOP?
Object-Oriented Programming in Dart helps organize code using classes and objects. It makes code reusable, maintainable, and easier to understand by modeling real-world entities and their relationships.
// Simple OOP example in Dart
class Car {
String brand = 'Toyota';
void start() {
print('$brand car is starting!');
}
}
void main() {
Car myCar = Car();
myCar.start();
}
Core OOP Principles
Encapsulation
Bundle data and methods together
class BankAccount {
double _balance = 0; // Private
void deposit(double amount) {
_balance += amount;
}
}
Inheritance
Create new classes from existing ones
class Animal {
void eat() => print('Eating');
}
class Dog extends Animal {
void bark() => print('Woof!');
}
Polymorphism
Same method, different behaviors
class Shape {
void draw() => print('Drawing shape');
}
class Circle extends Shape {
void draw() => print('Drawing circle');
}
Abstraction
Hide complex implementation details
abstract class Vehicle {
void start(); // Must be implemented
void stop() {
print('Vehicle stopped');
}
}
🔹 Basic Class Example
Here's a simple class that demonstrates OOP concepts:
class Student {
// Properties (attributes)
String name;
int age;
List subjects = [];
// Constructor
Student(this.name, this.age);
// Methods (behaviors)
void addSubject(String subject) {
subjects.add(subject);
print('$name enrolled in $subject');
}
void displayInfo() {
print('Student: $name, Age: $age');
print('Subjects: ${subjects.join(', ')}');
}
}
void main() {
// Creating an object
Student student1 = Student('Alice', 20);
student1.addSubject('Math');
student1.addSubject('Physics');
student1.displayInfo();
}
Output:
Alice enrolled in Math
Alice enrolled in Physics
Student: Alice, Age: 20
Subjects: Math, Physics
🔹 Why Use OOP in Dart?
Object-Oriented Programming provides several benefits:
Benefits of OOP:
- Code Reusability: Write once, use multiple times
- Modularity: Break complex problems into smaller parts
- Maintainability: Easy to update and modify code
- Security: Hide sensitive data using encapsulation
- Real-world Modeling: Represent real entities as objects
// Real-world example: Library System
class Book {
String title;
String author;
bool isAvailable = true;
Book(this.title, this.author);
void borrow() {
if (isAvailable) {
isAvailable = false;
print('$title has been borrowed');
} else {
print('$title is not available');
}
}
void returnBook() {
isAvailable = true;
print('$title has been returned');
}
}