loading...

Polymorphism in Dart: Part 3

kcooperdev profile image Khalif Cooper ・1 min read

We will be continuing our series on objected oriented programming. This article will be a bit short as we discussed it indirectly in the previous article. Need a hint? This principle involves method overriding. So next we are moving on to our topic, polymorphism.

Poly, which means "many" and morph, meaning morphing into different forms or shapes. Together, Polymorphism, means creating many forms or configurations. A real world example of polymorphism would be if we are buying a car feature. Lets' say a new car feature was just released. The feature is to enable self driving. The result is the car will still drive no matter. But if we modify the driving feature or function and update it. Then instead of the basic automatic driving feature, we can update functionality, and the car can drive itself without human support.

In the real world this is Polymorphism. Polymorphism is updating or modifying a feature, function, or implementation that already exist in the parent's class.

An Programmatic Example of Polymorphism:


class Car{
  void driving(){
    print("driving car 1");
  }
}

class Honda extends Car{
  //override method overrides generic driving method
  @override
  void driving(){
    print("driving car 2");
    super.driving(); //calls generic driving method
  } 
}

void main(){ 
  Honda car1 =  new Honda();
  car1.driving();
}

output:
driving car 2
driving car 1

The @override annotation is a note/comment to let someone one know this method is overridden the generic method derived from the parent class. The keyword "super" calls the parent class. This sums of method overriding. Next up is inheritance. So, Stay tuned..

Posted on Apr 12 by:

kcooperdev profile

Khalif Cooper

@kcooperdev

I am a developer passionate about learning and teaching others about code. I am all about JS and Dart.

Discussion

markdown guide