Method Overriding

Method Overriding is the feature of compile time Polymorphism.In Which More than One  Method name is same but have different parameter/Signature in the same Class. At Compile time the compiler check which one is going to be call. 

   static void str(int x)
        {
            Console.WriteLine("interger");
        }
 
        static void str(string y)
        {
            Console.WriteLine("string");
        }
       
        public static void Main()
        {
            str("Mindstick");
        }
Out put :

Stirng

In this example I have maded two function with same name but given different parameter in first method it is of integer type and in another method I have given string type.When we compile this program it check first from the parameter given in the main function and it is of string type so it will call string type of method.

Method Overloading

Method Overloading is the feature of runtime polymorphism .In which more than one one method name is similar with same signature .But in different Classes.Method Overriding use two keywords that is Virtual and Override.Virtual in Base Class/Parent Class and Override in Inheritence Class/Child Class.It is Possible in Derived class only by the help of virtual or abstract keyword.

Let us take a example to understand Method Overriding

using System;
 
 namespace ConsoleApplication2
{
    class Program
    {
        class Parent
        {
            public virtual int balance()
            {
                return 10;
            }
            public Parent()
            {
              Console.WriteLine("Im in Parent Constructor");
            }
        }
 
        class Child : Parent
        {
            public override int balance()
            {
                return 20;
            }
 
 
            static void Main(string[] args)
            {
                Child obj = new Child();               
                var val = obj.balance();
                Console.WriteLine(val);
                Console.Read();
 
 
 
            }
        }
 
 
       
      
    }
}


Output


Method overloadind and Method Overriding in C#



In the above example child class is inheriting parent class it have two method with same name and have same argument and from main class I have maken the object of class and called balace .


You can also visit these useful related post

Method Overloading and Overriding in C#

Method Overloading in C#

How is method overriding different from method overloading?

Why method overloading is not possible by changing the return type in java

Thank you..

  Modified On Jun-04-2018 03:48:15 AM

Leave Comment