TCSObject-Oriented ProgrammingEasy

What is the difference between method overloading and overriding?

JavaOOPPolymorphism

Question

Explain method overloading and method overriding in Java with examples.

Answer

Method Overloading:

- Same method name, different parameters

- Compile-time polymorphism

- Can have different return types

- Within the same class


Method Overriding:

- Same method signature in parent and child class

- Runtime polymorphism

- Must have same return type (or covariant)

- In different classes (inheritance)


Example:

// Overloading
class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}

// Overriding
class Animal {
    void makeSound() { System.out.println("Animal sound"); }
}

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

Explanation

Overloading is resolved at compile time based on method signature, while overriding is resolved at runtime based on the actual object type.