overriding vs overloading

overriding vs overloading

Method Overloading

Method overloading occurs when two or more methods in the same class have the same name but different parameters (type, number, or both).

overriding vs overloading

Key Points:

  • Same Class: Overloaded methods must be in the same class or inherited from a superclass.
  • Different Parameters: Must have different parameter lists.
  • Return Type: Can have the same or different return types, but the return type alone is not enough to distinguish overloaded methods.
  • Compile-time Polymorphism: Overloading is resolved at compile time.

Example:

Example
```java
public class MathUtils {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Overloaded method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Overloaded method to add two doubles
    public double add(double a, double b) {
        return a + b;
    }
}
```

Method Overriding

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

Key Points:

  • Different Classes: The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
  • Same Parameters: The parameter list must be identical.
  • Same Return Type: The return type must be the same or a subtype (covariant return type) of the return type in the superclass method.
  • Run-time Polymorphism: Overriding is resolved at runtime.
  • `@Override` Annotation: Often used to indicate a method is overriding a superclass method. It is optional but recommended for better readability and compile-time checking.

Example:

Example
```java
class Animal {
    // Method to be overridden
    public void makeSound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    // Overriding the makeSound method
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

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

Summary

Method overloading involves defining multiple methods with the same name but different parameters in the same class, resolved at compile time. Method overriding involves a subclass providing a specific implementation of a method already defined in its superclass, resolved at runtime.

Homepage

Readmore