Cambo Freelance
HomeServicesArticlesTutorialsTeamCoursesContact
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

Send us a message

Ready to start your project? Get in touch with our team.

Contact Us

Services

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

Useful Links

  • Home
  • Services
  • Learning
  • About Us
  • Contact
  • Pricing

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsDartPolymorphism in Dart
🎯Dart Tutorials

97 lessons

Beginner(35)0Complete Dart Tutorial Series — Course Index1Introduction to Dart2Installing Dart SDK3Setting Up VS Code for Dart4DartPad Online Editor5Hello World in Dart6Dart Syntax7Comments in Dart8Variables in Dart9Data Types in Dart10Strings in Dart11Numbers in Dart12Booleans in Dart13Type Conversion in Dart14Constants in Dart: final and const15User Input in Dart16Arithmetic Operators in Dart17Assignment Operators in Dart18Comparison Operators in Dart19Logical Operators in Dart20Null-Aware Operators in Dart21If Statement in Dart22If Else in Dart23Else If in Dart25Switch Statement in Dart26Ternary Operator in Dart27For Loop in Dart28While Loop in Dart29Do While Loop in Dart30Break and Continue in Dart32Nested Loops in Dart33Functions in Dart35Optional Parameters in Dart37Arrow Functions in Dart38Recursive Functions in Dart
Intermediate(34)39Lists in Dart40Sets in Dart41Maps in Dart42Collection Operations in Dart
Advanced(28)73Futures in Dart74Async and Await in Dart75Streams in Dart76
🎯

Dart Tutorials

Lesson 56 of 97

All lessons
Beginner (35)0Complete Dart Tutorial Series — Course Index1Introduction to Dart
43
Spread Operator and Collection Literals in Dart
44Collection If in Dart
45Collection For in Dart
46Null Safety in Dart
47Nullable Variables in Dart
48Null Assertion Operator in Dart
49Late Keyword in Dart
50Required Keyword in Dart
51Classes and Objects in Dart
52Constructors in Dart
53Getters and Setters in Dart
54Static Members in Dart
55Interfaces in Dart
56Polymorphism in Dart
57Inheritance in Dart
58Method Overriding in Dart
59Abstract Classes in Dart
60Abstract Classes vs Interfaces in Dart
61Mixins in Dart
62Extension Methods in Dart
63Exception Handling in Dart
64Try-Catch in Dart
65Finally Block in Dart
66Custom Exceptions in Dart
67Generics in Dart
68Typedef in Dart
69Enums in Dart
70Records in Dart
71Pattern Matching in Dart
72Cascade Notation in Dart
Stream Controllers in Dart
77Isolates in Dart
78File Operations in Dart
80JSON Parsing in Dart
82HTTP Requests in Dart
83REST API Client in Dart
84Dart Packages and pub.dev
85Testing in Dart
86Dart CLI Applications
87Dart Code Style and Best Practices
88Server-side Dart with Shelf
89Introduction to Flutter
90Flutter Widgets and Layouts
91Flutter State Management
92Flutter Navigation and Routing
93Project: Calculator in Dart
94Project: Temperature Converter in Dart
95Project: Age Calculator in Dart
96Project: Todo CLI App in Dart
97Project: Student Management System in Dart
98Project: Expense Tracker in Dart
100Project: Banking System in Dart
101Project: Inventory Management System in Dart
102Project: Contact Manager in Dart
103Project: Mini REST API Backend in Dart
2
Installing Dart SDK
3Setting Up VS Code for Dart
4DartPad Online Editor
5Hello World in Dart
6Dart Syntax
7Comments in Dart
8Variables in Dart
9Data Types in Dart
10Strings in Dart
11Numbers in Dart
12Booleans in Dart
13Type Conversion in Dart
14Constants in Dart: final and const
15User Input in Dart
16Arithmetic Operators in Dart
17Assignment Operators in Dart
18Comparison Operators in Dart
19Logical Operators in Dart
20Null-Aware Operators in Dart
21If Statement in Dart
22If Else in Dart
23Else If in Dart
25Switch Statement in Dart
26Ternary Operator in Dart
27For Loop in Dart
28While Loop in Dart
29Do While Loop in Dart
30Break and Continue in Dart
32Nested Loops in Dart
33Functions in Dart
35Optional Parameters in Dart
37Arrow Functions in Dart
38Recursive Functions in Dart
Intermediate (34)39Lists in Dart40Sets in Dart41Maps in Dart42Collection Operations in Dart43Spread Operator and Collection Literals in Dart44Collection If in Dart45Collection For in Dart46Null Safety in Dart47Nullable Variables in Dart48Null Assertion Operator in Dart49Late Keyword in Dart50Required Keyword in Dart51Classes and Objects in Dart52Constructors in Dart53Getters and Setters in Dart54Static Members in Dart55Interfaces in Dart56Polymorphism in Dart57Inheritance in Dart58Method Overriding in Dart59Abstract Classes in Dart60Abstract Classes vs Interfaces in Dart61Mixins in Dart62Extension Methods in Dart63Exception Handling in Dart64Try-Catch in Dart65Finally Block in Dart66Custom Exceptions in Dart67Generics in Dart68Typedef in Dart69Enums in Dart70Records in Dart71Pattern Matching in Dart72Cascade Notation in Dart
Advanced (28)73Futures in Dart74Async and Await in Dart75Streams in Dart76Stream Controllers in Dart77Isolates in Dart78File Operations in Dart80JSON Parsing in Dart82HTTP Requests in Dart83REST API Client in Dart84Dart Packages and pub.dev85Testing in Dart86Dart CLI Applications87Dart Code Style and Best Practices88Server-side Dart with Shelf89Introduction to Flutter90Flutter Widgets and Layouts91Flutter State Management92Flutter Navigation and Routing93Project: Calculator in Dart94Project: Temperature Converter in Dart95Project: Age Calculator in Dart96Project: Todo CLI App in Dart97Project: Student Management System in Dart98Project: Expense Tracker in Dart100Project: Banking System in Dart101Project: Inventory Management System in Dart102Project: Contact Manager in Dart103Project: Mini REST API Backend in Dart
🎯DartIntermediateLesson 56 of 97Dart TeamJune 19, 2026

Polymorphism in Dart

Master Dart polymorphism — subtype polymorphism, runtime method dispatch, interface-based polymorphism, the is/as operators, and real-world payment processing examples.


Table of Contents

  1. What is Polymorphism?
  2. Subtype Polymorphism
  3. Runtime Type Dispatch
  4. Interface-Based Polymorphism
  5. Full Example
  6. Exercise
  7. Quiz
  8. Summary

What is Polymorphism?

Polymorphism (from Greek: "many forms") means that a single interface can represent objects of different types. In Dart, polymorphism lets you write code that works with a parent type, while at runtime different subclass behaviors execute. This is the foundation of flexible, extensible object-oriented design.

Subtype Polymorphism

A subclass object can be used anywhere the parent class type is expected:

class Animal {
  String name;
  Animal(this.name);

  // This method will be overridden by subclasses
  String speak() => ''...'';

  void describe() => print(''$name says: \$${speak()}'');
}

class Dog extends Animal {
  Dog(String name) : super(name);
  @override String speak() => ''Woof!'';
}

class Cat extends Animal {
  Cat(String name) : super(name);
  @override String speak() => ''Meow!'';
}

class Parrot extends Animal {
  final String phrase;
  Parrot(String name, this.phrase) : super(name);
  @override String speak() => phrase;
}

void main() {
  // All stored as Animal type — polymorphic
  List<Animal> animals = [
    Dog(''Rex''),
    Cat(''Whiskers''),
    Parrot(''Polly'', ''Polly wants a cracker!''),
    Dog(''Buddy''),
  ];

  for (var animal in animals) {
    animal.describe();  // correct speak() called at runtime
  }
}
Output:
Rex says: Woof!
Whiskers says: Meow!
Polly says: Polly wants a cracker!
Buddy says: Woof!

Runtime Type Dispatch

Dart dispatches method calls based on the actual runtime type of the object, not the declared type. Use is to check types and as to cast:

void processAnimal(Animal animal) {
  animal.describe();  // polymorphic

  // Type-specific logic with is
  if (animal is Dog) {
    print(''  $${animal.name} can fetch!'');
  } else if (animal is Parrot) {
    print(''  $${animal.name} can mimic: "$${animal.phrase}"'');
  }
}

void main() {
  processAnimal(Dog(''Max''));
  processAnimal(Cat(''Luna''));
  processAnimal(Parrot(''Rio'', ''Pretty bird!''));
}

Interface-Based Polymorphism

abstract class Drawable {
  void draw();
  String get description;
}

class Circle extends Drawable {
  final double radius;
  Circle(this.radius);
  @override void draw() => print(''Drawing circle r=$radius'');
  @override String get description => ''Circle(r=$radius)'';
}

class Square extends Drawable {
  final double side;
  Square(this.side);
  @override void draw() => print(''Drawing square s=$side'');
  @override String get description => ''Square(s=$side)'';
}

class Triangle extends Drawable {
  final double base, height;
  Triangle(this.base, this.height);
  @override void draw() => print(''Drawing triangle b=$base, h=$height'');
  @override String get description => ''Triangle(b=$base, h=$height)'';
}

// Works with ANY Drawable — polymorphic
void drawAll(List<Drawable> shapes) {
  for (var shape in shapes) {
    shape.draw();
    print(''  -> \$${shape.description}'');
  }
}

void main() {
  drawAll([Circle(5), Square(4), Triangle(3, 6), Circle(2)]);
}

Full Example: Payment Processing

abstract class PaymentMethod {
  String get name;
  bool validate();
  Future<bool> processPayment(double amount);
}

class CreditCard extends PaymentMethod {
  final String cardNumber;
  final String cvv;
  CreditCard(this.cardNumber, this.cvv);

  @override String get name => ''Credit Card'';
  @override bool validate() => cardNumber.length == 16 && cvv.length == 3;

  @override
  Future<bool> processPayment(double amount) async {
    await Future.delayed(Duration(milliseconds: 200));
    print(''Credit card charged: \$\$${amount.toStringAsFixed(2)}'');
    return true;
  }
}

class PayPal extends PaymentMethod {
  final String email;
  PayPal(this.email);

  @override String get name => ''PayPal'';
  @override bool validate() => email.contains(''@'');

  @override
  Future<bool> processPayment(double amount) async {
    await Future.delayed(Duration(milliseconds: 150));
    print(''PayPal transfer: \$\$${amount.toStringAsFixed(2)} from $email'');
    return true;
  }
}

class PaymentProcessor {
  // Works with any PaymentMethod — polymorphic
  Future<void> charge(PaymentMethod method, double amount) async {
    print(''Processing via \$${method.name}...'');
    if (!method.validate()) {
      print(''Validation failed for \$${method.name}'');
      return;
    }
    final success = await method.processPayment(amount);
    print(success ? ''Payment successful!'' : ''Payment failed.'');
  }
}

void main() async {
  var processor = PaymentProcessor();
  await processor.charge(CreditCard(''1234567812345678'', ''123''), 49.99);
  await processor.charge(PayPal(''user@example.com''), 29.99);
}
Output:
Processing via Credit Card...
Credit card charged: $49.99
Payment successful!
Processing via PayPal...
PayPal transfer: $29.99 from user@example.com
Payment successful!

Exercise

  1. Create an abstract Notification class with send(String message). Implement EmailNotification, SMSNotification, and PushNotification. Write a NotificationService that sends to a list of Notification objects.
  2. Create a Serializer abstract class with serialize(Map data) and deserialize(String input). Implement JsonSerializer and CsvSerializer.

Quiz

1. What does polymorphism mean in OOP?

  • A) A class with many fields
  • B) An object that can take many forms — one interface, multiple implementations ✅
  • C) Multiple inheritance
  • D) A method with many parameters

2. What determines which overridden method is called at runtime?

  • A) The declared (compile-time) type
  • B) The actual runtime type of the object ✅
  • C) The order of class declaration
  • D) The variable name

3. What Dart keyword checks whether an object is a certain type?

  • A) typeof
  • B) as
  • C) is ✅
  • D) instanceof

Summary

Polymorphism allows one interface to represent many types. Store different subclass objects in a parent-type list and call methods — each object responds with its own overridden behavior. Use is for runtime type checks (with automatic smart cast) and as for explicit downcasting. Interface-based polymorphism (via abstract class + implements) keeps code flexible and testable — swap implementations without changing calling code.

dartprogrammingintermediateoop
PreviousLesson 55: Interfaces in DartNextLesson 57: Inheritance in Dart
Back to All Tutorials