What is mean by method overloading and method overriding? And what is the difference between them?

Method Overloading: Method overloading allows programmers to use the same name for multiple methods. Methods are differentiated with their number and type of parameters. Method overloading is an example of compile-time polymorphism.

For Example:

class Car
{
        public void Print()
        {
            Console.WriteLine("Without Parameter");
        }

        public void Print(int type)
        {
            Console.WriteLine("With Parameter");
        }
}

class Program
{
        static void Main(string[] args)
        {
            Car car = new Car();
            car.Print();
            car.Print(1);
            Console.ReadKey();
        }

                }

              

             //Output:

               Without Parameter

               With Parameter

 

There are different scenarios related to method overloading, which we will see in the output section of this ebook.

 

Method Overriding: Method overriding allows programmers to create base classes methods override in derived classes with the same and same signature. It is a run time polymorphism. Virtual and override keywords are used for the method overriding.

 

 class Vehicles
 {
        public virtual void Print()
        {
            Console.WriteLine("Base Class");
        }
 }

 class Car: Vehicles
 {
        public override void Print()
        {
            Console.WriteLine("Derived Class");
        }
 }

 class Program
 {
        static void Main(string[] args)
        {
            Vehicles vehicle = new Car();
            vehicle.Print();

            Car car = new Car();
            car.Print();

            Vehicles vehicles = new Vehicles();
            vehicles.Print();

            Console.ReadKey();
        }

               }

 

             //Output :

               Derived Class

               Derived Class

               Base Class

            

             Difference between method overloading and method overriding:

Method Overloading

Method Overriding

Creating a new method with the same name and different signature in the same class is called method overloading.

Creating a new method with the same name and signature in the derived class same as the base class is called method overriding.

It is called a compile-time polymorphism.

It is called Run-time polymorphism.

Access modifier can be any.

The access modifier is public only.

Method overloading doesn’t need an inheritance

Method overriding needs inheritance.


 

Post a Comment

0 Comments