Run Time PolyMorphism Example---4 For Beginner??????

Sabarimahesh
Posted by Sabarimahesh under C# category on | Points: 40 | Views : 2467
 class Program
{
static void Main(string[] args)
{
Baseclass bc;
bc = new Baseclass();
bc.Show();
bc = new DerivedClass();
bc.Show();
bc = new DerivedClass2();
bc.Show();
Console.ReadLine();

}

}

class Baseclass
{
public virtual void Show()
{
System.Console.WriteLine("Baseclass::Show");
}
}

class DerivedClass : Baseclass
{
public override void Show()
{
System.Console.WriteLine("DerivedClass::Show");
}
}

class DerivedClass2 : DerivedClass
{
public override void Show()
{
System.Console.WriteLine("DerivedClass2::Show");
}
}



OutPut


Baseclass::Show
DerivedClass::Show
DerivedClass2::Show


The function Show() of Base class Baseclass is declared as virtual, while the implementation of Show() in successive Derived classes is decorated with the modifier override. Next, we succesively create objects of each class and store their reference in base class reference variable Baseclass and invoke Show(). The rite versions of Show get invoked based on the object the reference variable refers to.

Comments or Responses

Login to post response