Difference between overloading and overriding?

🔁 Method Overloading (Compile-Time Polymorphism)

✨ What It Is:

Overloading occurs when multiple methods have the same name but different parameter lists. These methods can exist in the same class or in a subclass.

✅ Key Rules:

  • Must have different number, type, or order of parameters.
  • Can have different return types.
  • Happens at compile time (the compiler decides which version to call based on the arguments).
class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(2, 3));          // Output: 5
        System.out.println(c.add(2.5, 3.5));      // Output: 6.0
        System.out.println(c.add(1, 2, 3));       // Output: 6
    }
}

🔄 Method Overriding (Runtime Polymorphism)

✨ What It Is:

Overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

✅ Key Rules:

  • Method name, return type, and parameters must match exactly.
  • Must occur across parent-child class relationship.
  • Happens at runtime (which method gets called depends on the object’s actual type).
  • Use @Override annotation to make it explicit.
  • Access modifier can’t be more restrictive than in the parent.

🔧 Example:

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound();  // Output: Dog barks
    }
}

🧠 Comparison Table

FeatureMethod OverloadingMethod Overriding
Class RelationshipHappens in the same classRequires inheritance (parent-child)
Method SignatureMust be different (parameters)Must be exactly same
Return TypeCan varyMust be same or covariant (subtype)
Access ModifierAny (private, public, etc.)Cannot be more restrictive than superclass
Static MethodsCan be overloadedCannot be overridden (can only be hidden)
Polymorphism TypeCompile-time polymorphismRuntime polymorphism
Binding TimeDecided at compile timeDecided at runtime
Annotation UseOptionalRecommended to use @Override

Leave a Reply

Your email address will not be published. Required fields are marked *