Page Stats
Visitor: 182
Virtual Method or Method Overriding
Inheritance is a mechanism of inheriting, but sometimes some properties should be modified according to the need like a son inherits legs from his parents but his walking style is different. This is known as Overriding. Using this concept derived class can modify the features of base class. Method Overriding is a concept of polymorphism and very important in terms of dynamic decisions.
The primary difference between method overloading and overriding is that overloading takes place within the same class whereas when the method in the sub class performs different functionality, it is referred to as overriding. The method that is to be overridden has to be given a modifier virtual and the derived class that overrides this method should specify the modifier override for the method.
Example 3 : Overridden class method.
class Class1 { public void method1() { Console.WriteLine("This is Class 1 - method 1"); } public virtual void method2() { Console.WriteLine("This is Class 1 - method 2"); } } class Class2: Class1 { public void method1() { Console.WriteLine("This is Class 2 - method 1"); } public override void method2() { Console.WriteLine("This is Class 2 - method 2"); } } class Program { static void Main(string[] args) { Class2 obj = new Class2(); Class1 obj2 = obj; obj2.method1(); obj2.method2(); Console.Read(); } }