Use of new,Virtual,Override key words with small example program

muralikrishnasurap-12704
Posted by muralikrishnasurap-12704 under C# category on | Points: 40 | Views : 1992
class Base
{
public void show()
{
Console.WriteLine("Base class Show method");
}
public void Show1()
{
Console.WriteLine("Base class Show1 method");
}
public virtual void Show2()
{
Console.WriteLine("Base class Show2 method");
}

}
class derived : Base
{
public void show()
{
Console.WriteLine("derived class Show method");
}
public new void Show1()
{
Console.WriteLine("derived class Show1 method");
}
public override void Show2()
{
Console.WriteLine("derived class Show2 method");
}

}
class Example2
{
static void Main(string[] args)
{
Base _obj = new Base();
_obj.show();
_obj.Show1();
_obj.Show2();
Console.Read();

Base _obj1 = new derived();
_obj1.show();
_obj1.Show1();//Don't expect that this will get call derived class method this "the new key word just hide the method.
_obj1.Show2();//in case of this method we had overriden so this method will get call from derived method of show2();
Console.Read();

derived _obj2 = new derived();
_obj2.show();
_obj2.Show1();
_obj2.Show2();
Console.Read();


}
}



Output:
Base class show method
Base class show1 method
Base class show2 method


Base class show method
Base class show1 method
derived class show2 method


derived class show method
derived class show1 method
derived class show2 method

Comments or Responses

Login to post response