Hiprup

What is method overloading vs method overriding?

Both are forms of polymorphism but at different times.

Overloading — same method name, different parameter list (number/type/order). Resolved at compile time (static binding). Lives in the same class.

Overriding — subclass provides a new implementation of an inherited method with the same signature. Resolved at runtime (dynamic dispatch). Annotated with @Override.

Rules — overriding cannot reduce visibility or throw broader checked exceptions; static, private, and final methods cannot be overridden.

public class Calculator {
    // Method OVERLOADING - same name, different parameters
    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 class Animal {
    public void speak() {
        System.out.println("Animal speaks");
    }
}

public class Dog extends Animal {
    @Override  // Method OVERRIDING - same signature in subclass
    public void speak() {
        System.out.println("Dog barks");
    }
}

// Runtime polymorphism
Animal animal = new Dog();
animal.speak(); // "Dog barks" — resolved at runtime

// Compile-time polymorphism
Calculator calc = new Calculator();
calc.add(1, 2);       // calls add(int, int)
calc.add(1.5, 2.5);   // calls add(double, double)

Calculator has three add methods differentiated by parameters (overloading — resolved at compile time by argument types). Dog overrides Animal's speak method (overriding — resolved at runtime by object type).

The variable animal is typed as Animal but the object is Dog, so Dog.speak() is called.

Key distinctions: overloading = same class, different params, compile time. Overriding = subclass, same signature, runtime.

Know the overriding rules (access modifier, exceptions, final/static/private). The @Override annotation is a best practice for catching errors.

What is method overloading vs method overriding? | Hiprup