Middle
What can be changed when overloading methods or operators?
sobes.tech AI
Answer from AI
Overloading allows you to change:
- Parameter list: number, order, or types of parameters.
- Return type: can differ (for methods). For operators, the return type determines the operation semantics.
- Access modifiers: can vary.
You cannot change:
- Only the return type (without changing the parameter list).
- Only the access modifiers (without changing the parameter list).
Example of method overloading in Java:
class Calculator {
// Overloading method add: int + int
public int add(int a, int b) {
return a + b;
}
// Overloading method add: double + double
public double add(double a, double b) {
return a + b;
}
// Overloading method add: int + int + int
public int add(int a, int b, int c) {
return a + b + c;
}
}
Example of overloading the "+" operator in C++ for a user-defined class:
class Vector {
public:
int x, y;
Vector(int x = 0, int y = 0) : x(x), y(y) {}
// Overloading the + operator
Vector operator+(const Vector& other) const {
return Vector(x + other.x, y + other.y);
}
};
Comparison table of the original and overloaded method (example):
| Aspect | Original method add(int a, int b) |
Overloaded method add(double a, double b) |
|---|---|---|
| Method name | add |
add |
| Parameters | int a, int b |
double a, double b |
| Quantity | 2 | 2 |
| Types | int, int | double, double |
| Return type | int | double |
| Modifier | public | public |