What is Method Overriding?
Method overriding in C# allows programmers to create base classes that allows its inherited classes to override same name methods when implementing in their class for different purpose. This method is also used to enforce some must implement features in derived classes.
- Method overriding is only possible in derived classes, not within the same class where the method is declared.
- Base class must use the virtual or abstract keywords to declare a method. Then only can a method be overridden
Example:
class MethodOverriding_Example
{
static void Main(string[] args)
{
College c = new College();
Console.WriteLine(c.CourseName());
Console.ReadLine();
}
}
public class Student
{
public virtual string CourseName()
{
return "C#";
}
}
public class College : Student
{
public override string CourseName()
{
return "C++";
}
}
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.