Answer
Method Overloading vs Method Overriding
Method Overloading — Compile-Time Polymorphism
Same method name, different parameter list in the same class.
Java
public class Calculator {
// Overloaded methods — same name, different params
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String add(String a, String b) {
return a + b;
}
}
Calculator c = new Calculator();
c.add(1, 2); // calls int version
c.add(1.0, 2.0); // calls double version
c.add(1, 2, 3); // calls 3-arg version
c.add("Hello", " World"); // calls String version
Rules for Overloading:
- ✓Must change parameter type, number, or order
- ✓Return type alone is NOT enough to overload
- ✓Can have different return types (but must also differ in params)
✦
Method Overriding — Runtime Polymorphism
Subclass redefines a method from the parent class with the same signature.
Java
class Animal {
public void sound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Meow!");
}
}
// Runtime polymorphism — decided at runtime
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.sound(); // "Woof!"
a2.sound(); // "Meow!"
Rules for Overriding:
- ✓Same method name, same return type, same parameters
- ✓Cannot override
static,final, orprivatemethods - ✓
@Overrideannotation is recommended (compiler catches mistakes) - ✓Overriding method cannot throw broader checked exceptions
✦
Comparison Table
| Aspect | Overloading | Overriding |
|---|---|---|
| Class | Same class | Parent + Child class |
| Parameters | Must differ | Must be same |
| Return type | Can differ | Must be same (or covariant) |
| Binding | Compile-time (static) | Runtime (dynamic) |
| Polymorphism | Compile-time | Runtime |
@Override | Not needed | Recommended |
| Static methods | Can be overloaded | Cannot be overridden |
In Automation
Java
// Overloading — click method with different wait times
public void click(By locator) { ... }
public void click(By locator, int timeoutSeconds) { ... }
// Overriding — each page implements its own setup
class BasePage {
public void waitForPageLoad() { ... }
}
class CheckoutPage extends BasePage {
@Override
public void waitForPageLoad() {
// Wait for specific checkout elements
wait.until(ExpectedConditions.visibilityOf(totalAmount));
}
}
