What is Multi-level inheritance in Dart?

Dart inheritance

Inheritance refers to a class’s capability to derive properties and behaviors from another class.

Dart allows one class to inherit from another, generating a new class from an existing one. We use the extend keyword to inherit from another class.

Multi-level inheritance

In Dart, multi-level inheritance occurs when various classes inherit in a chain (i.e., one class extends a parent class, and another class extends the class that extended the parent class). A subclass is inherited by another subclass or forms an inheritance chain.

Terminology in Inheritance

  • Parent class: This is the class from which the child class inherits its properties. It is also known as the base class or the superclass.
  • Child class: This is the class that inherits the properties of another class. It is also known as the subclass or the derived class.

Syntax

class A{
...
}

class B extends A{
...
}

class C extends B{
...
}

Figure

The figure below shows the visual representation of Multi-level inheritance in Dart:

Visual representation of Multi-level inheritance

Code

The following code shows the implementation of the multi-level inheritance:

class Shape{
void display(){
// creating method
print("This is Shape class");
}
}
class Triangle extends Shape{
// creating method
void showInfo(){
print("This is Triangle class");
}
}
class Circle extends Triangle{
// creating method
void showMessage(){
print("This is Circle class");
}
}
void main(){
// Creating an object of class Circle
var circle = Circle();
// invoking Circle's method using Circle's object
circle.showMessage();
// invoking Triange's method using Circle's object
circle.showInfo();
// invoking Shape's method using Circle's object
circle.display();
}

Code explanation

We create three different classes named Shape, Triangle, and Circle with methods display(), showInfo(), and showMessage(), respectively. In the main drive, we create an object of the Circle class and then invoke the methods of the parent class that the class extends.

Note: Dart does not support multiple inheritances.

Free Resources