What is the difference between overloading a method and overriding a method? Can anyone explain it with an example?
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.
}
}