Google News
logo
Dart - Interview Questions
Explain the types of inheritance in Dart.
In Dart, inheritance is a fundamental concept of object-oriented programming that allows classes to inherit properties and behaviors from other classes. There are three types of inheritance that can be implemented in Dart:

1.  Single inheritance :

   * Single inheritance refers to the ability of a class to inherit properties and behaviors from a single superclass.

   * In Dart, classes can extend only one superclass at a time, resulting in a single inheritance hierarchy.

   * The subclass inherits all the accessible instance variables, methods, and getters/setters from the superclass.

Example :
     class Animal {
       void eat() {
         print('The animal is eating.');
       }
     }
     
     class Dog extends Animal {
       void bark() {
         print('The dog is barking.');
       }
     }​

2. Multiple inheritance :

   * Multiple inheritance refers to the ability of a class to inherit properties and behaviors from multiple superclasses.

   * Unlike some other programming languages, Dart does not support multiple inheritance, where a class can directly inherit from multiple superclasses.

   * However, Dart provides a mechanism called "mixin" that allows the reuse of code from multiple sources. Mixins are implemented using the `with` keyword.

   * Mixins provide a form of multiple inheritance by applying a mixin class to another class, allowing it to inherit the properties and behaviors of the mixin.

Example :
     class A {
       void methodA() {
         print('Method A');
       }
     }
     
     class B {
       void methodB() {
         print('Method B');
       }
     }
     
     class C with A, B {
       void methodC() {
         print('Method C');
       }
     }​
3. Hierarchical inheritance :

   * Hierarchical inheritance refers to a situation where multiple subclasses inherit from a common superclass.

   * Each subclass has its own set of additional properties and behaviors in addition to the inherited ones from the superclass.

   * The subclasses may further extend the inherited properties and behaviors to form their own unique hierarchy.

Example :
     class Animal {
       void eat() {
         print('The animal is eating.');
       }
     }
     
     class Dog extends Animal {
       void bark() {
         print('The dog is barking.');
       }
     }
     
     class Cat extends Animal {
       void meow() {
         print('The cat is meowing.');
       }
     }​


* In Dart, single inheritance is the primary form of inheritance, allowing classes to extend a single superclass.

* Multiple inheritance is not directly supported, but mixins can be used to achieve similar functionality by applying multiple mixins to a class.

* Hierarchical inheritance is a common pattern where multiple subclasses inherit from a common superclass, forming a hierarchical structure.
Advertisement