Overriding Method in C#


in C# we can override default method.you need to override the method of a super class in a sub class to change the functionality of super class method. today we will create see how to override method use in C#.

Overriding Method In C#


In C# we can create virtual method that can overriden in deriven class.We need to override the method of super class in a subclass to change fuctionality of super class method of C#.
Virtualy method must be explicitly define in the base class.We use virtual keyword to indicate that you want to have based method overridden in aderived class.
In given code we override the method:

using System;
using System.Collections.Genric;
using System.Text;
namespace overrideexample

{

public class Person

{

private int fAge;

public Person()

{

Age =21;
}
public virtual void setAge(int age)

{

fage=age;

}

public virtual int getAge()

{

return fAge;

}
}

public class AdultPerson:Person
{

public AdultPerson()
{
}

override public void setAge(int age)
{
if(age>21)
base.setAge(age);

}
}

class Program
{
static void Main(string[]args)

{
Person p= new Person();
p.setage(18);
ap= new AdultPerson();
ap.setAge(18);
Console.WriteLine("Person Age:{0}",p.setAge());
Console.WriteLine("Adultperson Age:{0}",ap.getAge());
}
}
}

In the above code, virtual keyword is used to create virtual methods. setAge() and getAge() in the person base class. These virtual methods are overridden in the derived class. AdultPerson with the override keyword.
OUTPUT OF THE CODE IS
Person Age:18
AdultPerson Age:21
Press any key to continue....


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: