The feature that allows different methods with the same name but different implementations is called method overloading (or function overloading). It enables a class to have multiple methods sharing the same name but differing in the number, type, or sequence of parameters. This allows a single method call to execute different code depending on the arguments provided, enhancing code readability and flexibility. Key points about method overloading:
- Methods must differ in their parameter lists (number, type, or order of parameters) to be considered overloaded.
- Overloaded methods cannot be distinguished solely by their return type.
- It is a form of compile-time polymorphism (static polymorphism), where the method to invoke is determined at compile time.
- Method overloading promotes code reusability and maintainability by allowing multiple behaviors under a single method name.
- It differs from method overriding, which involves redefining a method in a subclass with the same signature and is related to runtime polymorphism.
For example, in Java:
java
void add(int a, int b) { ... }
void add(int a, int b, int c) { ... }
void add(float a, float b) { ... }
These are overloaded add
methods with different parameter lists