119

What is the difference between overloading and overriding.

5
  • 2
    @james: did you at least try google?? Mar 23, 2009 at 15:02
  • I'm guessing you're not going to get this one.
    – Jon B
    Mar 23, 2009 at 15:09
  • james- probably not and I feel quite silly not being able to explain a simple concept
    – james
    Mar 23, 2009 at 15:26
  • 1
    @james my guess is you intuited these concepts without knowing the terms. I'm going to guess you're self-taught. You should probably pick up a beginner level C# book, not to learn but to reinforce what you already know. It's mind-numbing but will help immensely in tech interviews. Mar 23, 2009 at 15:44
  • you can read more on this link : intquesans.blogspot.com/2011/05/…
    – asd
    May 29, 2011 at 17:51

12 Answers 12

250

Overloading

Overloading is when you have multiple methods in the same scope, with the same name but different signatures.

//Overloading
public class Test
{
    public void GetStuff(int id)
    {}
    public void GetStuff(string name)
    {}
}

Overriding

Overriding is a principle that allows you to change the functionality of a method in a child class.

//Overriding
public class Test
{
        public virtual void GetStuff(int id)
        {
            //Get stuff default location
        }
}

public class Test2 : Test
{
        public override void GetStuff(int id)
        {
            //base.GetStuff(id);
            //or - Get stuff new location
        }
}
4
  • 1
    @cgreeno i think you miss void for getStuff in test2
    – Mahdi
    Mar 2, 2015 at 20:04
  • 3
    just to mention that the base class method must be marked as virtual to override else you'll get a compilation error. May 21, 2015 at 18:38
  • Hey, this might be old but I still have a question about this. Does overloading make it available to have more functionality with 'one' method? Like I can do this: getStuff(2, "Hello world!"); or I can do this getStuff("Myname", "Mysurname", "Hello World!");? Anyone can confirm this is the way to do it?
    – Sj03rs
    Aug 31, 2016 at 8:48
  • I think the Overriding example actually is Overwriting, override is when you super class method get override accidentaly or if you mean to do it by using the new keyword in both cases, override or overwrite, the behaivor is diferent when you declare Parent p = new Child(); p.Method(); ... maybe I'm wrong and it is just another way to do almost the same thing. Can anyone explaint it better than me? Feb 26, 2020 at 10:39
39

Simple definitions for overloading and overriding

Overloading (Compile Time Polymorphism):: Functions with same name and different parameters

public class A
{
    public void print(int x, int y)
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public void print(float x, float y)
    {
        Console.WriteLine("Overload child method");
    }
}

Overriding (Run Time Polymorphism):: Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

public class A
{
    public virtual void print()
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public override void print()
    {
        Console.WriteLine("Overriding child method");
    }
}
1
  • Perhaps you would like to add that the overriding concept applies for the parent class-sub class relationship.
    – Freakyuser
    Feb 27, 2013 at 6:56
12

I want to share an example which made a lot sense to me when I was learning:

This is just an example which does not include the virtual method or the base class. Just to give a hint regarding the main idea.

Let's say there is a Vehicle washing machine and it has a function called as "Wash" and accepts Car as a type.

Gets the Car input and washes the Car.

public void Wash(Car anyCar){
       //wash the car
}

Let's overload Wash() function

Overloading:

public void Wash(Truck anyTruck){
   //wash the Truck  
}

Wash function was only washing a Car before, but now its overloaded to wash a Truck as well.

  • If the provided input object is a Car, it will execute Wash(Car anyCar)
  • If the provided input object is a Truck, then it will execute Wash(Truck anyTruck)

Let's override Wash() function

Overriding:

public override void Wash(Car anyCar){
   //check if the car has already cleaned
   if(anyCar.Clean){ 
       //wax the car
   }
   else{
       //wash the car
       //dry the car
       //wax the car
   }     
}

Wash function now has a condition to check if the Car is already clean and not need to be washed again.

  • If the Car is clean, then just wax it.

  • If not clean, then first wash the car, then dry it and then wax it

.

So the functionality has been overridden by adding a new functionality or do something totally different.

1
  • 1
    This must be the answer. Voted+
    – Jack
    Feb 13, 2017 at 13:46
10
  • Overloading = Multiple method signatures, same method name
  • Overriding = Same method signature (declared virtual), implemented in sub classes

An astute interviewer would have followed up with:

What's the difference between overriding and shadowing?

1
  • Never knew it was called shadowing, good to know. The only relation overloading and overriding have is overing.
    – Samuel
    Mar 23, 2009 at 15:11
4

As Michael said:

  • Overloading = Multiple method signatures, same method name
  • Overriding = Same method signature (declared virtual), implemented in sub classes

and

  • Shadowing = If treated as DerivedClass it used derived method, if as BaseClass it uses base method.
3

Having more than one methods/constructors with same name but different parameters is called overloading. This is a compile time event.

Class Addition 
{
   int add(int a, int b) 
   {
     return a+b;
   }
   int add(int a, int b, int c)
   {
     return a+b+c;
   }

   public static main (String[] args) 
   {
     Addition addNum = new Addition();
     System.out.println(addNum.add(1,2));
     System.out.println(addNum.add(1,2,3));
   }
}

O/p:

3
6

Overriding is a run time event, meaning based on your code the output changes at run time.

class Car
{
    public int topSpeed() 
    {
        return 200;
    }
}
class Ferrari extends Car
{
    public int topSpeed()
    {
        return 400;
    }
    public static void main(String args[])
    {
        Car car = new Ferrari();
        int num= car.topSpeed();
        System.out.println("Top speed for this car is: "+num);
    }
}

Notice there is a common method in both classes topSpeed(). Since we instantiated a Ferrari, we get a different result.

O/p:

Top speed for this car is: 400
3

in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:

variant 1 without override: result is 200

    class Car {
        public int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

variant 2 with override keyword: result is 400

    class Car {
        public virtual int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public override int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract

1

shadowing = maintains two definitions at derived class and in order to project the base class definition it shadowes(hides)derived class definition and vice versa.

1

Another point to add.

Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.

int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)

Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.

Can overload class constructors, methods.

Can consider as Compile Time (static / Early Binding) polymorphism.

=====================================================================================================

Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.

Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.

Can Consider as Run Time (Dynamic / Late Binding) polymorphism.

Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx

=====================================================================================================

Helpful Links

http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism

1
  • Good one, with the needed details. May 4, 2016 at 19:05
1

Overloading is a part of static polymorphism and is used to implement different method with same name but different signatures. Overriding is used to complete the incomplete method. In my opinion there is no comparison between these two concepts, the only thing is similar is that both come with the same vocabulary that is over.

3
  • Captain here: Overloading a method gives you multiple signatures of different methods with the same name. Overriding hides an inherited member, either from classes or interfaces. flies away
    – SparK
    Oct 4, 2016 at 14:05
  • 1
    @SparK Overriding doesn't hide a member. You can either override or hide an inherited member. The two are mutually exclusive options.
    – Servy
    Oct 4, 2016 at 15:35
  • @Servy, wrong choice of words, I meant "substitutes".
    – SparK
    Oct 4, 2016 at 17:36
1

Overloading is the concept in which you have same signatures or methods with same name but different parameters and overriding, we have same name methods with different parameters also have inheritance is known as overriding.

0

Method overloading and Method overriding are 2 different concepts completely different. Method overloading is having the same method name but with different signatures. Method overriding is changing the default implementation of base class method in the derived class. Below you can find 2 excellent video tutorials explaining these concepts.

Method overriding Vs hiding

Method overloading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.