Saturday, January 12, 2013

Is it possible to overridden a function in subclass which is virtual in base class?


Overridden a function in subclass

Yes, to overridden a function in subclass, base class function should be declared as virtual.

Example

// Base class
class Parent
{
    public virtual int Calculation(int i, int j)
    {
        return i * j;
    }
}

 // Derive class
class child : Parent
{
    public override int Calculation(int i, int j)
    {
        return i / j;
    }
}

static void Main(string[] args)
{
    Parent obj = new Parent();
    int i = obj.Calculation(20, 10);
    Console.WriteLine(i);

    Parent obj1 = new child();
    int j = obj1.Calculation(20, 10);
    Console.WriteLine(j);
}

Output

200
2

No comments:

Post a Comment