OOP in Dart - A Complete Guide

OOP in Dart - A Complete Guide

Object-Oriented Programming (OOP) in Dart

Dart is an object-oriented language that supports key OOP principles:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

1. Encapsulation (Data Hiding)

Encapsulation restricts direct access to object properties and provides controlled access via methods.

class BankAccount {
  String _accountNumber;
  double _balance;

  BankAccount(this._accountNumber, this._balance);

  double get balance => _balance;

  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
      print("Deposited: \$${amount}, New Balance: \$${_balance}");
    }
  }

  void withdraw(double amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
      print("Withdrawn: \$${amount}, Remaining Balance: \$${_balance}");
    }
  }
}

2. Abstraction (Hiding Implementation Details)

abstract class Animal {
  void makeSound();
}

class Dog extends Animal {
  @override
  void makeSound() {
    print("Woof! Woof!");
  }
}

3. Inheritance (Code Reusability)

class Vehicle {
  String brand;
  int year;

  Vehicle(this.brand, this.year);
}

class Car extends Vehicle {
  String model;

  Car(String brand, int year, this.model) : super(brand, year);
}

4. Polymorphism (Multiple Forms of a Method)

class Shape {
  void draw() {
    print("Drawing a shape...");
  }
}

Additional Features

Mixins

mixin Flyable {
  void fly() {
    print("Flying high!");
  }
}

class Bird with Flyable {}

Static Members

class MathUtils {
  static double pi = 3.14159;
  static double square(double num) => num * num;
}

Comments

Popular Posts