Inheritance in Dart

Inheritance In Dart

Inheritance is the concept of creating a new class with the basic blueprint of the existing class. The child class will contain all the attributes and methods of the parent class as well can create its own.

Advantages

  • It promotes reusability of the code and reduces redundant code.
  • It makes code simpler, cleaner and saves time and money on maintenance.
  • It facilitates the creation of class libraries.
  • It can be used to enforce standard interface to all children classes.

Syntax

class ChildClassName extends ParentClassName
Info

Note: The extends keyword is used for inheriting from parent class.

Example

class Animal {
  var animalName;
  var numberOfLegs;
  var lifeSpan;

  Animal({this.animalName, this.numberOfLegs, this.lifeSpan});

  void displayAnimalDetails() {
    print("Animal name: " + animalName);
    print("Number of Legs: " + numberOfLegs.toString());
    print("Life Span: " + lifeSpan);
  }
}

class Cat extends Animal {
  void meow() {
    super.displayAnimalDetails();
    print('This is Cat, cat does meow.');
  }
}

void main(List<String> args) {
  var cat = Cat();
  cat.animalName = "Cat";
  cat.numberOfLegs = "4";
  cat.lifeSpan = "12-18 years";
  cat.meow();
}
Show Output