In this chapter you will learn:
- What is Runtime Polymorphism?
- How to implement it in program?
What is Runtime Polymorphism?
Runtime Polymorphism is also known as Dynamic Polymorphism, Late Binding
, Method overriding
etc. Whereas in static polymorphism we overload a function; in dynamic polymorphism we override a base class function using virtual or override keyword. Method overriding means having two or more methods with the same name, same signature but with different implementation.
Programming Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RuntimePolymorphism { class Program { static void Main(string[] args) { Chocolate ch = new Chocolate(); ch.flavor(); Console.ReadKey(); } } class IceCream { public IceCream() { Console.WriteLine("Class : Icecream"); } public virtual void flavor() { Console.WriteLine("IceCream Type : Vanilla"); } } class Chocolate : IceCream { public Chocolate() { Console.WriteLine("Class : Chocolate"); } public override void flavor() { Console.WriteLine("IceCream Type : Chocolate"); } } }
Output
Class : Icecream
Class : Chocolate
IceCream Type : Chocolate
_
GuideLine:
- If base class function is marked as virtual then it is compulsory to add override keyword in derived class function.
- Virtual method allows child class to their own implementation of derived methods.
- Virtual method cannot be declared as private.
https://www.completecsharptutorial.com/basic/c-abstract-and-virtual-method-inheritance-tutorial-with-code/
Summary
In this chapter, you learned Runtime Polymorphism implementation using Virtual and Override keyword. In the next chapter, some programming examples are there that will help you to understand polymorphism clearly.