Learn Dart · 8/12

Object-Oriented Programming (OOP) Part 2: Advanced Concepts

7 min read

Welcome back, coder! ☕️

In Part 1, we built the bricks (Classes and Objects). Now, we are going to learn how to be the architect. If you just stack bricks on top of each other without a plan, you get a wall. If you use the concepts below, you get a skyscraper (or at least a very well-structured dog house).

We are diving into the "DRY" principle (Don't Repeat Yourself) and making our code modular, safe, and reusable.


1. Inheritance and the extends Keyword

The Problem: Copy-Paste Nightmares

Imagine you are building a system for a Zoo.
You create a Lion class with eat() and sleep() methods.
Then you create a Tiger class with eat() and sleep() methods.
Then a Bear...

Suddenly, you realize you need to change how sleep() works. You now have to update it in 50 different files. This is a maintenance disaster. 😫

The Solution: Inheritance

Inheritance allows you to create a "parent" class (Superclass) that holds the common logic, and "child" classes (Subclasses) that inherit that logic automatically.

Definition: Inheritance is a mechanism where a new class derives properties and characteristics from an existing class.

How it works

In Dart, we use the extends keyword.

  • Parent (Superclass): The general concept (e.g., Animal).
  • Child (Subclass): The specific version (e.g., Lion).

Code Example

dart
// The Parent
class Animal {
  String name;
  
  Animal(this.name);
  
  void eat() {
    print('$name is munching on food. 🍖');
  }
  
  void sleep() {
    print('$name is sleeping. Zzz... 😴');
  }
}

// The Child
// Lion gets everything Animal has, for free!
class Lion extends Animal {
  // We pass the name up to the parent using 'super'
  Lion(String name) : super(name);
  
  void roar() {
    print('ROAAAR! 🦁');
  }
}

void main() {
  var simba = Lion('Simba');
  simba.eat();  // Inherited from Animal
  simba.roar(); // Specific to Lion
}

Method Overriding (@override)

Sometimes the parent's way of doing things isn't specific enough. A generic animal sleeps, but a bat sleeps upside down.

You can override the parent's method to provide a specific implementation.

dart
class Bat extends Animal {
  Bat(String name) : super(name);

  @override // Good practice to annotate this
  void sleep() {
    // We can even call the parent's original method if we want
    super.sleep(); 
    print('...but hanging upside down. 🦇');
  }
}

Industry Tip: Dart supports Single Inheritance. A class can only extend one other class. You cannot say class Dog extends Animal, Pet. We solve this limitation later with Mixins.


2. Abstract Classes and Abstract Methods

The Problem: The "Ghost" Object

Let's look at our Animal class again.
If I write var thing = Animal('Generic Thing');, what is it? It has no shape, no specific sound, no habitat. It shouldn't really exist as a concrete object in your game or app. It's just a concept.

Also, if we have a method makeSound() in Animal, what sound does it make? We don't know yet.

The Solution: Abstraction

We make the class Abstract. This tells Dart: "Hey, this class is just a template. Don't let anyone create an object of this directly."

Definition: An abstract class is a class that cannot be instantiated. It is used to define a base for subclasses.

Code Example

dart
abstract class Shape {
  // Abstract method: It has no body (no curly braces).
  // Child classes MUST implement this, or the compiler will yell at you.
  double calculateArea();
  
  // Normal method: Inherited as usual
  void printInfo() {
    print('I am a shape.');
  }
}

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

  @override
  double calculateArea() {
    return 3.14 * radius * radius;
  }
}

void main() {
  // var s = Shape(); // ERROR! Cannot instantiate abstract class.
  var c = Circle(5); // This works.
  print(c.calculateArea());
}

Why use this?

It enforces consistency. If you build a UI library, you might have an abstract Button class. You force every developer who makes a specific button (Like BlueButton or RedButton) to write a onClick function, ensuring they don't forget it.


3. Implicit Interfaces and the implements Keyword

The Problem: "I want to be two things at once"

Remember how we said a class can only extend one parent?
What if you have a Duck?
It is an Animal.
But it is also a Flyable thing (like an Airplane).
And it is a Swimmable thing (like a Submarine).

Inheritance (extends) implies an "IS-A" relationship (A Duck IS-A Animal).
Interfaces imply a "ACTS-AS" relationship (A Duck ACTS-AS Flyable).

The Solution: Interfaces

Fact: Dart does not have a specific interface keyword like Java or C#. Instead, every class is implicitly an interface.

When you use implements, you are signing a contract. You promise to include every single method and variable from that class in your new class, but you don't inherit the logic. You have to write the logic yourself.

Code Example

dart
// Acts as the interface
class Flyable {
  void fly() {
    print('Flying high!');
  }
}

class Swimmable {
  void swim() {
    print('Swimming deep!');
  }
}

class Duck implements Flyable, Swimmable {
  // We MUST override everything from the interfaces.
  // We do NOT get the print statements from above. We define our own.
  
  @override
  void fly() {
    print('The duck flaps wings frantically.');
  }

  @override
  void swim() {
    print('The duck paddles.');
  }
}

Wait, why use implements if I have to rewrite the code?
It allows for Polymorphism. You can have a list of List<Flyable> that contains Ducks, Airplanes, and Superheroes. You know for a fact they all have a fly() method, even if they implement it differently.


4. Mixins: Adding Features Without Inheritance

The Problem: The Diamond of Death 💎

We want to share code (unlike implements where we rewrite it) but we don't want strict inheritance.
If Duck extends Bird and Airplane extends Vehicle, how do they both share the exact same fly() code without copy-pasting?

The Solution: Mixins

Mixins are Dart's superpower. They allow you to "snap on" capabilities to a class. It's like a video game character equipping an item.

Definition: Mixins are a way of reusing a class’s code in multiple class hierarchies.

How it works

  1. Define a mixin using mixin.
  2. Apply it using with.

Code Example

dart
mixin Logger {
  void log(String msg) {
    print('LOG [${DateTime.now()}]: $msg 📝');
  }
}

mixin Musical {
  void playNote() {
    print('Do Re Mi... 🎵');
  }
}

// A Smartphone is a Device (inheritance), 
// but it has Logger capabilities (mixin), 
// and Musical capabilities (mixin).
class Smartphone extends Device with Logger, Musical {
  void startUp() {
    log('Phone is starting...'); // Using the mixin code!
    playNote(); // Using the mixin code!
  }
}

class Device {}

void main() {
  var iPhone = Smartphone();
  iPhone.startUp();
}

The on Keyword (Advanced)

You can restrict a mixin so it can only be used on certain classes.

dart
mixin Swimmer on Animal {
  // This mixin can ONLY be used by classes that extend Animal
}

🧠 Interesting Fact

Flutter (the UI framework built on Dart) uses Mixins everywhere. The animation system heavily relies on SingleTickerProviderStateMixin. If you see a long name like that in Flutter, it's usually a Mixin giving your widget superpowers.


Summary: Which one should I use?

Concept Keyword Relationship Does it share code? Multiple?
Inheritance extends "Is a" ✅ Yes ❌ No (Single)
Interface implements "Acts as" ❌ No (Contract only) ✅ Yes
Mixin with "Has a capability" ✅ Yes ✅ Yes

📚 References & Further Reading

  1. Dart Language Tour (Classes) - The bible of Dart OOP.
    https://dart.dev/language/classes
  2. Mixins in Dart - Official guide on how mixins work under the hood.
    https://dart.dev/language/mixins
  3. Effective Dart: Design - Best practices for designing classes.
    https://dart.dev/effective-dart/design

Challenge for you! 🛠️

Create an abstract class Employee.
Create a mixin Coder that has a method writeCode().
Create a class SoftwareEngineer that extends Employee and uses Coder.
Go try it in DartPad!

Challenge

Challenge: The Digital Media Library

You are tasked with designing the class structure for a digital media library. Your system needs to handle different types of media like books, movies, and music albums, each with shared and unique characteristics and functionalities.

Your goal is to correctly use abstract classes, interfaces, mixins, and inheritance to create a flexible and non-repetitive class model.

Requirements:

  1. MediaItem Abstract Class:

    • Create an abstract class named MediaItem to serve as the base for all media types.
    • It must have two String properties: title and creator.
    • It must have a constructor to initialize these properties.
    • It must define an abstract method String getDetails() that returns a description of the item.
  2. Playable Interface:

    • Define a class Playable that will serve as an implicit interface.
    • This interface should define two method signatures: void play(); and void stop();. Classes that implement this are considered playable media.
  3. Downloadable and Sharable Mixins:

    • Create a mixin named Downloadable. It should contain a method void download() that prints a message like "Downloading '[title]'...", where [title] is the title of the media item.
    • Create another mixin named Sharable. It should contain a method void share(String platform) that prints a message like "Sharing '[title]' on [platform]...".
  4. Concrete Media Classes:

    • Book:

      • Must inherit from MediaItem.
      • Must use the Downloadable and Sharable mixins.
      • Must have an additional integer property pageCount.
      • Must implement the getDetails() method to return a string in the format: "Book: [title] by [creator], [pageCount] pages".
    • Movie:

      • Must inherit from MediaItem.
      • Must implement the Playable interface.
      • Must use the Downloadable and Sharable mixins.
      • Must have an additional integer property durationInMinutes.
      • Must implement getDetails(), play(), and stop().
      • getDetails() should return: "Movie: [title] directed by [creator], [durationInMinutes] mins".
      • play() should print: "Playing movie '[title]'...".
      • stop() should print: "Stopping movie '[title]'...".
    • Album:

      • Must inherit from MediaItem.
      • Must implement the Playable interface.
      • Must use the Sharable mixin (but not Downloadable).
      • Must have an additional integer property trackCount.
      • Must implement getDetails(), play(), and stop().
      • getDetails() should return: "Album: [title] by [creator], [trackCount] tracks".
      • play() should print: "Playing album '[title]'...".
      • stop() should print: "Stopping album '[title]'...".

Complete the class definitions in the editor to satisfy all the requirements.

Expected result

Your final code should contain the complete definitions for the Book, Movie, and Album classes that correctly use extends, implements, and with to meet all the requirements specified in the instructions.

  • Book class:

    • class Book extends MediaItem with Downloadable, Sharable
    • Contains int pageCount property and a constructor that initializes all properties including those from the superclass.
    • Overrides getDetails() to return the specified string format including pageCount.
  • Movie class:

    • class Movie extends MediaItem with Downloadable, Sharable implements Playable
    • Contains int durationInMinutes property and a constructor.
    • Overrides getDetails() to return the specified movie format.
    • Provides implementations for play() and stop() as required by the Playable interface.
  • Album class:

    • class Album extends MediaItem with Sharable implements Playable
    • Contains int trackCount property and a constructor.
    • Overrides getDetails() to return the specified album format.
    • Provides implementations for play() and stop() as required by the Playable interface.

The methods within the mixins (download, share) and implemented interfaces (play, stop) should use the print function as described in the instructions to indicate their actions.

dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.