Polymorphism in Dart

Updated 6 June 2023

Save

We are already familiar with the term Polymorphism, which means having multiple forms. Polymorphism in Dart is also the same as in other languages.

There are two types of polymorphism that are Function Overloading(Compile-time) and Function Overriding(Run-time)

Dart is a dynamically typed language and Function overloading requires static types, so Function Overloading is not supported in Dart.

Now let’s explore more on polymorphism.

You may also check our Flutter app development page.

Runtime Polymorphism in Dart

Runtime polymorphism works at the run time as the name suggests. In this form of polymorphism, the method from the superclass can be overridden to perform a new type of work according to the requirements.

Let’s explain this with some examples.

Let’s create a parent class with some method performing a certain task.

In the above code, VehicleClass has a method rideVehicle() which performs bicycle riding. In other words, “Ride bicycle” is printed.

Now, the VehicleClass is inherited by two other classes BikeClass and CarClass like below.

We created an instance of the BikeClass as a bike and an instance of CarClass as the car in our main() method.

Above all, BikeClass and CarClass are inherited from VehicleClass so they can execute the methods defined in the VehicleClass.

After that, we called the method rideVehicle() for both bike and car instances. Output is shown as “Ride bicycle” from both instances.

Above all, if the bike instance does not want to ride a bicycle and wants to ride a bike, then simply the BikeClass can override the rideVehicle() method of the parent class in its scope according to its requirement(here riding a bike instead of bicycle). The updated code will be like below.

This is known as method overriding or run-time polymorphism in Dart.

Advantages of Polymorphism

  1. Code Reusability: You can use the code written in the parent class in your child class and also modify it according to your requirements.
  2. Polymorphism enables us to communicate with a variety of distinct classes while hiding implementation details.

Conclusion

I hope I was able to provide the basic knowledge of polymorphism in Dart.

If you want to Explore more then visit here.

If you want to read my other articles please click here.

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home