What is the difference between method overloading and overriding?

user1662177 picture user1662177 · Sep 11, 2012 · Viewed 222.6k times · Source

What is the difference between overloading a method and overriding a method? Can anyone explain it with an example?

Answer

Hisham Muneer picture Hisham Muneer · Sep 11, 2012

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}