Inheritance in Dart: A Quick Example

Last updated on December 3, 2021 Pennywise Loading... Post a comment

In Dart, you can use the extends keyword with any class where 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 of 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

You May Also Like