5.1 Polymorphism
Last updated
Last updated
Right click on your solution
Go to Add > New Project and select Class Library
Name it Polymorphism
Polymorphism is the concept that a single method can behave differently depending on the object that calls it. Polymorphism helps to promote flexibility in designs by allowing the same method to have different implementations. There are three different types of polymorphism within C#.
Inheritance Based Polymorphism
Parametric Polymorphism
Overloading Polymorphism
In static polymorphism, the decision and response to a method is determined at compile time. Static polymorphism involves static binding or early binding. As the name indicates, early binding links a method with an object at compile time. Hence, calling of method should be done in compile time only.
Method overloading and operator overloading are the examples of static polymorphism.
In dynamic polymorphism, the decision and response to a method is determined at run time. Dynamic polymorphism involves late binding. Late binding or dynamic binding is a process of linking the method to an object during run time (run-time binding).
Method overriding is an example of dynamic polymorphism.
We have used some inheritance based polymorphism already in the previous modules. Inheritance based polymorphism is the ability to reuse the same methods within our inherited classes using virtual methods. Note that a virtual method is one that is declared as virtual in the base class and you can allow the subclasses of the type to override the virtual methods. If you look at our example from the previous module we have our base animal class with the methods GetMad()
and StateType()
. We reuse those same methods throughout our Bear, Cat, and PolarBear classes. However, those methods perform slightly different tasks depending on the object they are attached to. The override
and virtual
keywords allow this to be possible.
Base Class public virtual void StateType()
public virtual void GetMad()
Sub Class public override void StateType()
public override void GetMad()
We can incorporate the concept of polymorphism through our related classes (inheritance) by using the keyword override
.
We used parametric polymorphism within our Method Overloading module. Parametric polymorphism is where you have more than one method in your class that has the same name but they differ in their method parameters/return types. Let's look at the examples from the method overloading module.
Here we used polymorphism all within the same class. We have three methods named AnnounceGreatMusic()
but all three of them have different parameters. Later in our program when we call the AnnounceGreatMusic()
method, the compiler will be able to detect exactly which form of the method to use based on the parameters given.
Learn more about polymorphism.
Next: Encapsulation