![]() |
VOOZH | about |
In Dart, one class can inherit another class, i.e. dart can create a new class from an existing class. We make use of extend keyword to do so.
Terminology:
Example:
// parent class or base class or super class
class parent_class{
...
}
// child class or derived class or sub class
class child_class extends parent_class{
...
}
Important Points
- Child classes inherit all properties and methods except constructors of the parent class.
- Like Java, Dart also doesn't support multiple inheritance.
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class, and ‘B’ is a child class. Class ‘B’ inherits all the properties of class ‘A’.
Program :
Output:
Welcome to gfg!!
You are inside output function.
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
Program :
Output:
Welcome to gfg!!
You are inside the output function of Gfg class.
Welcome to gfg!!
You are inside the output function of GfgChild1 class.
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the image below, class A serves as a base class for the derived classes B, C, and D.
Program :
Output:
Welcome to gfg!!
You are inside output function of Gfg class.
Welcome to gfg!!
You are inside output function of Gfg class.
Welcome to gfg!!
You are inside output function of Gfg class.
Dart does not support multiple inheritance directly. This means a class cannot inherit from more than one parent class. However, Dart provides mixins as an alternative to achieve similar functionality.
Program:
Output :
This is class A.
This is class B.
This is class C.
Inheritance in Dart allows for code reuse and establishes a structured class hierarchy through the use of the extends keyword. Dart supports single inheritance, multilevel inheritance, and hierarchical inheritance; however, it does not permit multiple inheritance to reduce complexity. Instead, Dart offers mixins as a method for sharing code across multiple classes. Understanding inheritance is crucial for building scalable and maintainable applications.