Hi Friends, This article is asample of creating Virtual function.Before creating ,I will first mention its usage.
When you have a function defined in a class which you want to allow to be implemented by the inherited classes, you can use Virtual function The Virtual function could be implemented by the inherited classes in their own way and the call to the methos is decided at runtime.
The following code is an example of using Virtual function:
Using System; namespace VirtualFunction { Class Animal { Public Virtual void FoodHabits() { Console.WriteLine("Animals have different food habits:"); } } Class Carnivorous : Animal { Public Override void FoodHabits() { Console.WriteLine("The Carnivorous animals eat only meat"); } } Class Herbivorous: Animal { Public Override void FoodHabits() { Console.WriteLine("The Herbivorous animals eat only plants"); } } Class Implement { Public void callFunction(Animal Cr) { Cr.FoodHabits(); } } Class ClassMain { Public static void Main() { Implement Imp = new Implement(); Carnivorous cn = new Carnivorous(); Herbivorous hb = new Herbivorous(); Imp.callFunction(cn); Imp.callFunction(hb); Console.ReadLine(); } } }
In the preceding code, the base class named Animal has a virtual function named FoodHabits.The dervied classes Carnivorous and Herbivorous override the method FoodHabits of the base class Animal and implement their own functionality .The method named callFunction takes and argument of Animal class and calls FoodHabits() method to, which in turn will call the most appropriate derived method.
Friends this not copied from any other sites.This is example I did when i learnt C#.So, please don't misuse it. If this appreciatable rate this post
All the best, With Regards, Datta.G
|
No responses found. Be the first to respond and make money from revenue sharing program.
|