Junior
What is the difference between overloading and overriding a method?
sobes.tech AI
Answer from AI
Overloading methods and Overriding methods are mechanisms of polymorphism in object-oriented programming.
Overloading:
- Occurs within a single class or inheritance hierarchy but is not inherently related to inheritance.
- Involves having multiple methods with the same name but different signatures (number or types of parameters).
- The return type can be different or the same.
- The compiler determines which overloaded method to call based on the arguments provided at call time (static binding).
class Calculator {
// Method for adding two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method for adding two floating-point numbers
public double add(double a, double b) {
return a + b;
}
}
Overriding:
- Occurs only within an inheritance hierarchy.
- Involves having a method in a subclass with the same name, signature (number and types of parameters), and the same or covariant return type as the method in the parent class.
- Allows a specialized subclass to provide its own implementation of an inherited method.
- The Java Virtual Machine determines which overridden method to invoke at runtime based on the actual object's type (dynamic binding).
class Animal {
// Method that can be overridden in subclasses
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the makeSound() method
@Override // The @Override annotation is recommended for clarity and compile-time checking
public void makeSound() {
System.out.println("Woof!");
}
}
Key differences are summarized in the table:
| Attribute | Overloading | Overriding |
|---|---|---|
| Application | In a single class or inheritance hierarchy. | Only within an inheritance hierarchy. |
| Method name | Same. | Same. |
| Method signature | Different (number or types of parameters). | Same (number and types of parameters). |
| Return type | Can be different or the same. | Must be the same or covariant (subclass of the return type). |
| Method implementation | Different version of the method for different parameters. | Specialized implementation in a subclass. |
| Binding | Static (at compile time). | Dynamic (at runtime). |
| Access level | Can be different or the same. | Must be the same or more permissive than the parent. |
@Override annotation |
No. | Used for clarity and compile-time checking. |