Polymorphism
The article will give a real world example of what and how we apply polymorphism.
You heard that polymorphism is a combination of two words (Poly + Morphism).ploy means many, and Morphism means form which implies objects take many forms. That's simple but a little bit confusing to relate to the real world. To understand better we will go through an example.
Consider you are going to a shop to buy candy. You picked a candy and now you are in the cash counter to pay. Now you see there are lot of payment option like UPI, Cash, and Card. if we look closely we can see that payment as an action or object takes different forms like UPI, Card, and Cash. If the action takes a different form than static polymorphism and if an object takes a different form then dynamic polymorphism
We will look it in the code.
public void payment(upi){
//Payment using UPI
}
public void payment(card){
//Payment using card
}
public void payment(cash){
//Payment using cash
}
Based on the parameter and its type the payment we choose varies which is static polymorphism.
public class Payment{
void makePayment();
}
public class UpiPayment : Payment{
public void makePayment(){
//Payment using upi
}
}
public class CashPayment : Payment{
public void makePayment(){
//Payment using Cash
}
}
public class CardPayment : Payment{
public void makePayment(){
//Payment using card
}
}
Payment p = new CardPayment(); // Depending on what we use here our
// make payment varies
p.makePayment();
Here, The make payment function will called based on the object after the new keyword. This is called dynamic polymorphism.
I hope you enjoyed relating OOPs concept with real-world examples. If you have feedback comment below : )