Polymorphism is a fundamental object-oriented programming concept that allows objects of different classes to be treated as objects of a common superclass. In Dart, polymorphism is achieved through inheritance and method overriding.
In Dart, when a class inherits from a superclass, it automatically inherits the superclass's methods and properties. Polymorphism allows a subclass to provide its own implementation of a method defined in the superclass. This means that a subclass can override the behavior of a method inherited from its superclass and provide its own implementation that is specific to the subclass.
Here's an example to illustrate polymorphism in Dart :
class Animal {
void makeSound() {
print('The animal makes a sound.');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('The dog barks.');
}
}
class Cat extends Animal {
@override
void makeSound() {
print('The cat meows.');
}
}
void main() {
Animal animal = Animal();
Animal dog = Dog();
Animal cat = Cat();
animal.makeSound(); // Output: The animal makes a sound.
dog.makeSound(); // Output: The dog barks.
cat.makeSound(); // Output: The cat meows.
}​
In the example above, we have an `
Animal
` superclass and two subclasses, `
Dog
` and `
Cat
`. Each subclass overrides the `
makeSound()
` method inherited from the `
Animal
` class with its own implementation.
In the `
main()
` function, we create instances of `
Animal
`, `
Dog
`, and `
Cat
` and assign them to variables of type `
Animal
`. Despite the variables being of the `
Animal
` type, the polymorphic behavior allows us to call the `
makeSound()
` method on each object. The actual implementation of the method that gets executed depends on the type of the object. So, when we call `
makeSound()
` on the `
dog
` variable, the overridden `
makeSound()
` method from the `
Dog
` class is invoked, producing the output "
The dog barks."