OOP in Dart

Learn classes, objects, and heap memory

Object-Oriented Programming (OOP) in Dart


Definition

Object-Oriented Programming is a way to organize code using objects and classes. Classes are templates that define what data (properties) and actions (methods) an object should have.


Core Concepts


**Class**

A blueprint or template for creating objects.

  • Defines properties (data)
  • Defines methods (functions)
  • One class can create many objects

  • **Object (Instance)**

    A specific copy created from a class.

  • Has its own property values
  • Can call class methods
  • Created with the `new` keyword (or just the class name in Dart)

  • **Properties**

    Variables that belong to an object.

  • Store data about the object
  • Each object has its own copy
  • Accessed with dot notation: `object.property`

  • **Methods**

    Functions that belong to a class.

  • Actions an object can perform
  • Called with dot notation: `object.method()`

  • Example Structure

    `

    class ClassName {

    // Properties

    type propertyName;


    // Methods

    returnType methodName(parameters) {

    // method body

    }

    }


    // Create an object

    ClassName obj = ClassName();

    obj.propertyName = value;

    obj.methodName();

    `
    Cell2Dart
    // Simple class with properties class Person { String name = ''; int age = 0; } // Create a Person object Person person = Person(); person.name = 'Alice'; person.age = 30; print('${person.name} is ${person.age} years old'); // Create another object Person person2 = Person(); person2.name = 'Bob'; person2.age = 25; print('${person2.name} is ${person2.age} years old');

    Memory: Stack vs Heap


    Stack Memory

  • Stores simple variables (int, String, bool, double)
  • Stores references (memory addresses) to objects
  • Fast but limited size

  • Heap Memory

  • Stores actual objects
  • Objects live here after creation
  • Can be large but managed by garbage collector

  • When you create an object:

    1. A reference is created on the stack

    2. The actual object is created on the heap

    3. The reference points to the object on the heap

    Cell4Dart
    // Class with methods class Car { String brand = ''; String color = ''; void describe() { print('A $color $brand'); } } // Create and use objects Car car1 = Car(); car1.brand = 'Tesla'; car1.color = 'Red'; car1.describe(); Car car2 = Car(); car2.brand = 'BMW'; car2.color = 'Blue'; car2.describe();

    Practice

    CellcustomDart
    class Car { String brand = ''; String color = ''; } Car myCar = Car(); myCar.brand = 'Tesla'; myCar.color = 'Red'; print('${myCar.color} ${myCar.brand}');
    Run code to see objects in memory