Kinda Code
Home/Dart/Inheritance in Dart: A Quick Example

Inheritance in Dart: A Quick Example

Last updated: October 06, 2022

In Dart, you can use the extends keyword with any class when you want to extend the superclass’s functionality. A class can only extend one class since Dart does not support multiple inheritances.

Below is a quick example of implementing inheritance in Dart. Imagine we are building an employee management project for a company. The most general class will be Employee and other classes will inherit it:

import 'package:flutter/foundation.dart';

// Define the Employee class
class Employee {
  final String first;
  final String last;

  Employee(this.first, this.last);

  @override
  String toString() {
    return '$first $last';
  }
}

// Define the subclass which extends the Employee class
class Developer extends Employee {
  final String _role;

  Developer(this._role, String first, String last) : super(first, last);

  @override
  String toString() {
    return '${super.toString()}: $_role';
  }
}

void main() {
  final dev = Developer('Flutter Developer', 'John', 'Doe');
  debugPrint(dev.toString());
}

The preceding code will produce the following output:

John Doe: Flutter Developer

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Related Articles