Object-Oriented Programming (OOP) in Dart
Object-Oriented Programming (OOP) in Dart
Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
objects, which bundle data (attributes) and behavior (methods) together. It helps organize
code into reusable, maintainable structures. OOP is widely used in Flutter, as widgets
themselves are objects.
Real-World Example:
Instead of writing separate code for every car, we create a Car class and generate multiple
car objects from it.
Theory:
Example:
class Car {
String brand = "Toyota";
int speed = 0;
void accelerate() {
speed += 10;
print("The car is now going at $speed km/h");
}
}
void main() {
Car myCar = Car(); // Creating an object
print("Brand: ${myCar.brand}");
myCar.accelerate();
}
Task:
● Create a class Person with attributes name and age, and a method greet() that
prints a message.
2. Constructors
A constructor is a special method used to initialize an object when it is created.
Theory:
Example:
class Student {
String name;
int age;
void display() {
print("Student: $name, Age: $age");
}
}
void main() {
Student student1 = Student("Alice", 20);
student1.display();
}
Task:
● Modify the Person class to accept name and age through a constructor.
3. Encapsulation (Getters and Setters)
Encapsulation helps protect data by making variables private and exposing them via getters
and setters.
Theory:
Example:
class BankAccount {
double _balance = 0; // Private variable
void main() {
BankAccount account = BankAccount();
account.deposit(100);
print("Balance: \${account.balance}");
}
Task:
● Implement a Car class with private speed and a setter method to control
acceleration.
4. Inheritance
Inheritance allows a class to inherit properties and methods from another class.
Theory:
void main() {
Dog dog = Dog();
dog.makeSound(); // Inherited method
dog.bark();
}
Task:
● Create a Vehicle class and inherit it in Car and Bike classes with unique methods.
Theory:
Example:
class Shape {
void draw() {
print("Drawing a shape");
}
}
void main() {
Shape shape = Circle(); // Polymorphism
shape.draw();
}
Task:
● Create a Bird class with a fly() method, then create a subclass Eagle that
overrides fly().
Example:
abstract class Animal {
void makeSound(); // Abstract method
}
void main() {
Cat cat = Cat();
cat.makeSound();
}
Task:
Example:
mixin Logger {
void log(String message) {
print("LOG: $message");
}
}
void main() {
App myApp = App();
myApp.log("Application started");
}
Task:
● Create a mixin SoundMixin and use it in Dog and Cat classes to add a
makeSound() method.
Conclusion
OOP in Dart is crucial for writing structured, reusable, and scalable code. Mastering OOP
will help in Flutter development, as Flutter widgets are built using Dart’s OOP principles.