Saturday, 18 August 2018

C#: Method Overriding

Method overriding allows you to call sub class methods using super class reference variable. By using ‘virtual’ and ‘override’ keywords, you can achieve method overriding in C#.

Step 1: Define the super class method using virtual keyword.
public virtual void print(){

}

Step 2: Use ‘override’ keyword, while redefining the same method in sub classes.
public override void print(){
       
}

Program.cs
using System;

class A
{
    public virtual void print()
    {
        Console.WriteLine("I am in A");
    }
}

class B : A
{
    public override void print()
    {
        Console.WriteLine("I am in B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a= new B();
        a.print();
    }
}


Output
I am in B




Previous                                                 Next                                                 Home

No comments:

Post a Comment