Method Overriding in C#



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
The above code declares two classes, Student and College. The Student class is inherited from the College class. Method CourseName is overridden in the College class. The value of the CourseName method will be decided based on the caller program and its use of base class or derived class.


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.

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...