Skip to content

Runtime polymorphism

amit_gupta14

Asked Aug 4, 2009, 8:48 PM EDT1 answer
Share
LinkedInX
Looking for good practical example where we can use the concept of Run time polymorphism (Dynamic Dispatch Method).
I have seen the example but everytime I got that we are referring base class to child class and referring it's functions. But same can be done without it.
So why and when should we use runtime polymorphism? Looking for some good practical exmaple, illustrated with both runtime and without runtime.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Niradhip Chakraborty
    0
    Run time polymorphism means, complier would comes to know which method to execute, at the run time not in compile time.We can Implement the Run time polymorphism by using the Override Key word.And in the base class that method should be a virtual method class Animal{ public string Speak(){ return "Speak"; } } class Cat : Animal{ public override Speak(){ return "Meow"; } } class Dog : Animal{ public override Speak(){ return "Woof"; } } Now we create a few instances and call the method: Animal oTest; oTest = new Cat(); oTest.Speak(); //returns "Meow" oTest = new Dog(); oTest.Speak(); //returns "Dog" In this case we are working with the type "Animal". It's the interface of the superclass that the other types are derived from. We create instances of two different concrete types and call the same method on each, but get a different result. The sub classes provide the implementation to the superclass interface. Another example is something like the Console.Write() method which has many overloads. You call the method the same for different types. The method is polymorphic in that is handles each type in a different way.
    0