Dart – Concept of Inheritance
Last Updated :
15 Mar, 2023
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:
- Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or superclass.
- Child Class: It is the class that inherits the properties of the other classes. It is also known as a deprived class or subclass.
class parent_class{
...
}
class child_class extends parent_class{
...
}
Example 1: Example of Single Inheritance in the dart.
Dart
class Gfg{
void output(){
print( "Welcome to gfg!!\nYou are inside output function." );
}
}
class GfgChild extends Gfg{
}
void main() {
var geek = new GfgChild();
geek.output();
}
|
Output:
Welcome to gfg!!
You are inside output function.
Types of Inheritance:
- Single Inheritance: This inheritance occurs when a class inherits a single-parent class.
- Multiple Inheritance: This inheritance occurs when a class inherits more than one parent class. Dart doesn’t support this.
- Multi-Level Inheritance: This inheritance occurs when a class inherits another child class.
- Hierarchical Inheritance: More than one classes have the same 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.
Example 2:
Dart
class Gfg{
void output1(){
print( "Welcome to gfg!!\nYou are inside the output function of Gfg class." );
}
}
class GfgChild1 extends Gfg{
void output2(){
print( "Welcome to gfg!!\nYou are inside the output function of GfgChild1 class." );
}
}
class GfgChild2 extends GfgChild1{
}
void main() {
var geek = new GfgChild2();
geek.output1();
geek.output2();
}
|
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.
Example 3: Hierarchical inheritance.
Dart
class Gfg{
void output1(){
print( "Welcome to gfg!!\nYou are inside output function of Gfg class." );
}
}
class GfgChild1 extends Gfg{
}
class GfgChild2 extends Gfg{
}
void main() {
var geek1 = new GfgChild1();
geek1.output1();
var geek2 = new GfgChild2();
geek2.output1();
}
|
Output:
Welcome to gfg!!
You are inside output function of Gfg class.
Welcome to gfg!!
You are inside output function of Gfg class.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...