Saturday 10 March 2012

Overriding in C#


//Overriding demonstration
using System;
class Person
{
public virtual void Print()
{
Console.WriteLine("\nPrint Method Of Person Class\n");
}
}

class Student: Person
{
public override void Print()
{
Console.WriteLine("\nPrint Method Of Student Class\n");
}
}

class Program
{
static void Main()
{
//---------------First Method-------------------------
Person objPerson=new Person();
objPerson.Print();

Student objStudent=new Student();
objStudent.Print();
//----------------------------------------------------

//----------------Second Method-----------------------
// Accourding to runtime polymorphism base class reference can refer child class object

Person PersonObj;//Reference of Person class object

PersonObj=new Person(); // Pointing to base class object
PersonObj.Print();//Calling base class method Print()

PersonObj=new Student(); //Example of runtime polymorphism base class reference can refer child class object
PersonObj.Print();//Calling Drived class method Print()

//----------------------------------------------------
}
}

No comments:

Post a Comment