Dart Classes and Objects

Dart is an object-oriented language. Classes let you create blueprints for data and behavior. Objects are the actual instances you create from those blueprints.

What Is a Class

A class is like a cookie cutter. The cutter is the class — the cookie is the object. You define the shape once and stamp out as many cookies as you need.

  CLASS (blueprint)          OBJECT (real instance)
  ┌────────────────┐         ┌────────────────────┐
  │  Car           │  ──►    │  myCar             │
  │  - brand       │         │  brand = "Toyota"  │
  │  - speed       │         │  speed = 120       │
  │  - drive()     │         │  drive() works!    │
  └────────────────┘         └────────────────────┘

Defining a Class

class Car {
  String brand;
  int speed;

  // Constructor
  Car(this.brand, this.speed);

  // Method
  void drive() {
    print('$brand is driving at $speed km/h');
  }
}

Creating Objects

void main() {
  Car myCar = Car('Toyota', 120);
  Car friendCar = Car('Honda', 100);

  myCar.drive();      // Toyota is driving at 120 km/h
  friendCar.drive();  // Honda is driving at 100 km/h

  print(myCar.brand); // Toyota
}

Constructors

A constructor is a special function that runs when you create an object. It sets up the initial values.

Default Constructor

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

Person p = Person('Riya', 24);

Named Constructor

Named constructors let you create objects in different ways from the same class.

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  // Named constructor
  Person.guest() {
    name = 'Guest';
    age = 0;
  }
}

Person visitor = Person.guest();
print(visitor.name); // Guest

Getters and Setters

Getters and setters control how you read or write a class property — useful for adding validation.

class BankAccount {
  double _balance = 0;  // _ means private in Dart

  // Getter
  double get balance => _balance;

  // Setter with validation
  set balance(double amount) {
    if (amount >= 0) {
      _balance = amount;
    } else {
      print('Balance cannot be negative');
    }
  }
}

BankAccount account = BankAccount();
account.balance = 500;   // Uses setter
print(account.balance);  // Uses getter → 500
account.balance = -100;  // Prints error message

Inheritance

One class can extend another to inherit its properties and methods. Think of it as a child getting traits from a parent.

  Animal (parent)
  ├── name
  ├── eat()
  │
  ├── Dog (child) — inherits eat(), adds bark()
  └── Cat (child) — inherits eat(), adds meow()
class Animal {
  String name;
  Animal(this.name);

  void eat() {
    print('$name is eating');
  }
}

class Dog extends Animal {
  Dog(String name) : super(name);

  void bark() {
    print('$name says Woof!');
  }
}

Dog dog = Dog('Bruno');
dog.eat();   // Bruno is eating  (inherited)
dog.bark();  // Bruno says Woof! (own method)

Method Overriding

A child class can replace a parent method with its own version using @override.

class Animal {
  void makeSound() {
    print('Some sound');
  }
}

class Cat extends Animal {
  @override
  void makeSound() {
    print('Meow!');
  }
}

Cat cat = Cat();
cat.makeSound(); // Meow!

Abstract Classes

An abstract class is a class you cannot create objects from directly. It exists only to be extended by other classes.

abstract class Shape {
  double area(); // No body — child class must implement this
}

class Circle extends Shape {
  double radius;
  Circle(this.radius);

  @override
  double area() => 3.14 * radius * radius;
}

Circle c = Circle(5);
print(c.area()); // 78.5

Classes in Flutter

Flutter widgets are classes. When you write class MyApp extends StatelessWidget, you are creating a class that inherits from the built-in StatelessWidget class and overrides the build() method.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Text('Hello'));
  }
}

Key Points

  • Classes are blueprints; objects are real instances.
  • Constructors run when an object is created.
  • extends creates inheritance between classes.
  • @override replaces a parent method in the child.
  • Abstract classes enforce a contract — child classes must implement defined methods.

Leave a Comment

Your email address will not be published. Required fields are marked *