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 is a case of inheritance where a single class inherits from the parent class.
class parent_class{
...
}
class child_class extends parent_class{
...
}
The figure below visually represents single-level inheritance in Dart.
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();}
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
Cat
inherits thebreed
attribute from the parent classAnimal
.