Dart

19. Dart Pylymorphism

Understanding Polymorphism in Dart

Polymorphism is one of the key concepts in object-oriented programming. It means “many forms” and allows methods or classes to behave differently based on the object calling them. In Dart, polymorphism is achieved using inheritance and method overriding.

Key Points of Polymorphism

  1. A parent class reference can hold the object of its child class.
  2. The method implementation executed depends on the runtime object type.

Example of Polymorphism in Dart

// Base class
class Animal {
  void sound() {
    print("Animals make sound");
  }
}

// Derived class 1
class Dog extends Animal {
  @override
  void sound() {
    print("Dog barks");
  }
}

// Derived class 2
class Cat extends Animal {
  @override
  void sound() {
    print("Cat meows");
  }
}

void main() {
  // Polymorphic behavior
  Animal animal; // Base class reference

  // Assigning Dog object to Animal reference
  animal = Dog();
  animal.sound(); // Output: Dog barks

  // Assigning Cat object to Animal reference
  animal = Cat();
  animal.sound(); // Output: Cat meows
}


Real-World Scenario: Polymorphism Example

Imagine you are creating a system for a zoo, where different animals make different sounds, but all are treated as “Animal.”

abstract class Animal {
  void sound();
}

class Lion extends Animal {
  @override
  void sound() {
    print("Lion roars");
  }
}

class Elephant extends Animal {
  @override
  void sound() {
    print("Elephant trumpets");
  }
}

class Monkey extends Animal {
  @override
  void sound() {
    print("Monkey chatters");
  }
}

void main() {
  // List of animals
  List<Animal> animals = [Lion(), Elephant(), Monkey()];

  // Polymorphic behavior in action
  for (var animal in animals) {
    animal.sound();
  }
  
  // Output:
  // Lion roars
  // Elephant trumpets
  // Monkey chatters
}

Benefits of Polymorphism

  1. Flexibility: Code works with multiple object types in a unified way.
  2. Extensibility: New classes can be added with minimal changes to existing code.
  3. Reusability: You can reuse existing methods to work with different object types.

Leave a Reply

Your email address will not be published. Required fields are marked *