Inheritance in Dart: A Quick Example

Updated: October 6, 2022 By: A Goodman Post a comment

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles