Menu
Coddy logo textTech

Recap - Animal System

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 56 of 110.

challenge icon

Challenge

Easy

Let's build a complete animal system that brings together everything you've learned about mixins! You'll create a base Animal class, behavior mixins that use the on keyword, and specific animal classes that combine these capabilities in different ways.

You'll organize your code into three files:

  • animal.dart: Define your base class that all animals will inherit from:
    • An Animal class with a String name property and a constructor
    • A method describe() that prints [name] is an animal
  • behaviors.dart: Import the animal file and create three behavior mixins, each restricted to Animal using the on keyword:
    • A Swimming mixin with a method swim() that prints [name] is swimming
    • A Flying mixin with a method fly() that prints [name] is flying
    • A Walking mixin with a method walk() that prints [name] is walking
  • main.dart: Import both files and create three animal classes that combine inheritance with different mixin combinations:
    • A Duck class that extends Animal and uses all three mixins (Swimming, Flying, Walking)
    • A Fish class that extends Animal and uses only the Swimming mixin
    • A Bird class that extends Animal and uses Flying and Walking mixins
    Then demonstrate each animal's capabilities:
    • Create a Duck named 'Donald', call describe(), then swim(), fly(), and walk()
    • Print an empty line
    • Create a Fish named 'Nemo', call describe(), then swim()
    • Print an empty line
    • Create a Bird named 'Tweety', call describe(), then fly() and walk()

Each mixin can access the name property because of the on Animal constraint, ensuring type safety while providing flexible behavior composition.

Expected output:

Donald is an animal
Donald is swimming
Donald is flying
Donald is walking

Nemo is an animal
Nemo is swimming

Tweety is an animal
Tweety is flying
Tweety is walking

Try it yourself

import 'animal.dart';
import 'behaviors.dart';

// TODO: Create Duck class that extends Animal and uses Swimming, Flying, Walking mixins
class Duck {
  // TODO: Implement Duck class
}

// TODO: Create Fish class that extends Animal and uses only Swimming mixin
class Fish {
  // TODO: Implement Fish class
}

// TODO: Create Bird class that extends Animal and uses Flying and Walking mixins
class Bird {
  // TODO: Implement Bird class
}

void main() {
  // TODO: Create a Duck named 'Donald'
  // Call describe(), swim(), fly(), walk()
  
  // TODO: Print an empty line
  
  // TODO: Create a Fish named 'Nemo'
  // Call describe(), swim()
  
  // TODO: Print an empty line
  
  // TODO: Create a Bird named 'Tweety'
  // Call describe(), fly(), walk()
}

All lessons in Object Oriented Programming