Inheritance - Daily Learning

Tuesday, June 8, 2010

I always wonder that most of the people don't realize the importance of virtual and override words in the function. Everytime I ask, many (8 out of 10) of them tend to answer that virtual function can be overridden by child class. When you don't define base class function as virtual and child class function as override then also it overrides. So here I am going to show the difference with the following example in Console App.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inheritance
{
class Program
{
static void Main(string[] args)
{
CA ca = new CA();
CB cb = new CB();
CA cab = new CB();

ca.fun1();
ca.fun2();
ca.fun3();
ca.fun4();

cb.fun1();
cb.fun2();
cb.fun3();
cb.fun4();

cab.fun1();
cab.fun2();
cab.fun3();
cab.fun4();
Console.ReadLine();
}
}

public class CA
{
public void fun1()
{
Type type = GetType();
Console.WriteLine("CA: fun1");
}
public virtual void fun2()
{
Type type = GetType();
Console.WriteLine("CA: fun2");
}
public virtual void fun3()
{
Type type = GetType();
Console.WriteLine("CA: fun3");
}
public virtual void fun4()
{
Type type = GetType();
Console.WriteLine("CA: fun4");
}
}
public class CB:CA
{
public void fun1()
{
Type type = GetType();
Console.WriteLine("CB: fun1");
}
public void fun2()
{
Type type = GetType();
Console.WriteLine("CB: fun2");
}
public override void fun3()
{
Type type = GetType();
Console.WriteLine("CB: fun3");
}
public new void fun4()
{
Type type = GetType();
Console.WriteLine("CB: fun4");
}
}
}

It's out put is as follow



Labels: , ,

0 comments: