What is single-level inheritance in Dart?
Dart inheritance
Inheritance is a class’s capability to derive properties and behaviors from another class.
Dart allows one class to inherit from another and allows it to generate a new class from an existing one. To do this, we use the extend keyword.
Single-level inheritance
Single-level inheritance is a case of inheritance where a single class inherits from the parent class.
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 superclass.
- Child class: This is the class that inherits the properties of another class. It is also known as a subclass or derived class.
Syntax
class parent_class{
...
}
class child_class extends parent_class{
...
}
The figure below visually represents single-level inheritance in Dart.
Code
The following code shows how to implement single-level inheritance:
// Dart program to show hierarchical inheritance// Creating the parent classclass Animal{// Creating an attributeString breed;// Creating a functionvoid display(){print("This is the Animal class called Parent class");}}// Creating a child classclass Cat extends Animal{// Creating a functionvoid meow(){print("$breed meow everytime.");}}void main() {// Creating an object of the class Catvar cat = Cat();cat.breed = "Maine Coon";cat.meow();// Creating an object of the superclass Animalvar animal = Animal();animal.display();}
Code explanation
Line 5 to 12: We create the parent class called Animal, with the attribute breed and the function display().
Lines 14 to 20: We create a child class called Cat with the function meow(). It inherits the breed property of the parent class.
Lines 22 to 32: In the main drive, we create objects of the classes Cat and Animal. Finally, we assign value to the breed attribute using the class’ objects, and invoke the function.
Note: The class
Catinherits thebreedattribute from the parent classAnimal.