</>

Technology

Core Java

Difficulty

Beginner

Interview Question

What is the difference between method overloading and method overriding in Java?

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, or private methods
  • @Override annotation is recommended (compiler catches mistakes)
  • Overriding method cannot throw broader checked exceptions

Comparison Table

AspectOverloadingOverriding
ClassSame classParent + Child class
ParametersMust differMust be same
Return typeCan differMust be same (or covariant)
BindingCompile-time (static)Runtime (dynamic)
PolymorphismCompile-timeRuntime
@OverrideNot neededRecommended
Static methodsCan be overloadedCannot 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));
    }
}

Follow AutomateQA

Related Topics