Inheritance in Dart Programming


Inheritance in dart is defined as the process in which one class derive the properties and characteristics of another class. It is helpful as it provides an ability with which we can create a new class from an existing class.

Inheritance is a major component of a programming paradigm known as OOPS (Object-Oriented Programming).

With the help of Inheritance, one class can make use of all the properties and characteristics of another class.

In general, two classes are required for inheritance and these mainly are −

  • Parent class - A class that is inherited by the other class is known as the parent class. Sometimes, we also refer it to as the base class.

  • Child class - A class that inherits the properties and characteristics of the parent class is known as child class.

Syntax

The syntax for a class to inherit the properties and characteristics of another class looks something like this −

class Childclass extends ParentClass {
…
}

Whenever a child class wants to inherit the properties and characteristics of a parent class, we make use of the extends keyword.

There are different types of inheritance that are possible in Dart. Mainly these are −

  • Single level inheritance

  • Multi-level inheritance

  • Hierarchal inheritance

In this article, we will learn only about single level inheritance to keep things simple.

Single level Inheritance

Single level inheritance is that case of inheritance where a single class inherits from the parent class.

Example

Consider the example shown below −

 Live Demo

class Human{
   void walk(){
      print("Humans walk!");
   }
}

// inherting the parent class i.e Human
class Person extends Human{
   void speak(){
      print("That person can speak");
   }
}

void main(){
   Person p = new Person();
   p.speak();
   p.walk(); // invoking the parent class method
}

In the above example, we have two classes, named Human and Person respectively, the class named Human is the superclass and the class named Person is the child class, which is inheriting the method named walk() from the class named Human.

Output

That person can speak
Humans walk!

Updated on: 21-May-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements