Polymorphism in Dart

Polymorphism in Dart

Lets understand the world Polymorphism, it is made up of two words Poly and Morphism. Poly means many and Morphism means forms. So, Polymorphism means many forms.

Familiar with topic? Play Quiz

In programming, Polymorphism means that we can perform a single action in different ways.

For example, lets say we have a class Animal and we have a method makeSound(). Now, we have two classes Dog and Cat which extends Animal class. Now, we can override the makeSound() method in both Dog and Cat class and make them bark and meow respectively.

We can have a single method makeSound() but it is performing different actions in different classes. This is called Polymorphism.

In Dart, we can achieve Polymorphism by using Method Overriding.

What is Method Overriding?

Overriding methods is the process of redefining a method of a parent class in the child class.

This means that if there is a method in the parent class and the child class has the same method, then the method of the child class will be called while inheritance of any parent classes.

The method that we are overriding should be annotated with @override keyword in dart.

Example

class Animal {
  String name;
  int age;

  Animal(this.name, this.age);

  void eat() {
    print('$name is eating');
  }

  void sleep() {
    print('$name is sleeping');
  }
}

class Dog extends Animal {
  Dog(String name, int age) : super(name, age);

  void bark() {
    print('$name is barking');
  }

  @override
  void sleep() {
    print('$name is sleeping');
  }
} 


void main() {
  var dog = Dog('Bruno', 2);
  dog.eat();
  dog.sleep();
  dog.bark();
}

Output


Bruno is eating
Bruno is sleeping
Bruno is barking

code Try Yourself

Quiz