What is the difference between method overloading and method overriding?
Method Overloading
Definition: Allows multiple methods in the same class to have the same name but different parameter lists (number or type of parameters).
Binding: Achieved during compile-time (compile-time polymorphism).
Scope: Occurs within the same class.
Usage: Used to increase program readability by creating multiple methods that perform similar operations but with different inputs.
Example:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
Method Overriding
Definition: Allows a subclass to provide a specific implementation of a method already defined in its superclass.
Binding: Achieved during runtime (runtime polymorphism).
Scope: Requires inheritance; the subclass overrides the superclass method.
Usage: Used to define a behavior specific to the subclass, altering or enhancing the parent class behavior.
Example:
class Parent {
void display() { System.out.println(“Parent”); }
}
class Child extends Parent {
@Override
void display() { System.out.println(“Child”); }
}
Key Difference: Overloading occurs within a single class and is based on parameter variations, while overriding requires inheritance and involves redefining an existing method .