Virtual Methods / Method Overriding - Guess the Output

class A
{
    public virtual void ABC()
    {
        Console.WriteLine("A");
    }
}

class B : A
{
    public override void ABC()
    {
        Console.WriteLine("B");
    }
}

class C: B
{
    new public virtual void ABC()
    {
        Console.WriteLine("C");
    }
}

class X
{
    public static void Main()
    {
        A a = new C();
        B b = new C();
        C c = new C();

        a.ABC();
        b.ABC();
        c.ABC();
    }
}


Option 1: ABC
Option 2: BBA
Option 3: BBC
Option 4: AAB
Option 5: Error

Answer: Option 3: BBC

Explanation: While overriding, the type of object determine which method to be called. Method overriding is a feature that allows us to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and override to accomplish method overriding.

The method ABC() of base class A is declared as virtual, while the derived class's implementation of ABC() is decorated with override modifier. This enables C# to invoke methods like ABC() based on objects the reference variable refers to and not the type of reference that is invoking the function.

Hence in the above program when the instances "a" and "b" refers to the object of class C, the code goes to its base class B, since class B overrides the method ABC of its base class A, method ABC of class B is invoked in both the cases.

When create an object of type C and assign its reference to reference variable "c", ABC() method of class C is executed because the reference variable c refers to the object of class C.

No comments:

Post a Comment