Overriding vs. Overloading

  • Overloading is having two methods with the same name but different types or number of parameters (or both). A different return type as the sole difference between the two methods is not sufficient for overloading. The overloaded method is usually in the same class but it can also be in derived classes. An example of overloading is the helper find method in the recursive implementation of binary search from the previous chapter.

  • Overriding never happens in the same class. It always happens in subclasses. The overriding method must have the same signature as the overridden one in the superclass.

Java decides at compile time which version of an overloaded method must be invoked (static polymorphism). It decides at runtime which version of an overridden method shall be dispatched (dynamic polymorphism).

Consider the following code snippets:

public class Animal {

  // fields and constructors not shown!

  public void makeSound() {
    System.out.println("Grrr.......");
  }

  public void makeSound(int repeat) {
    for (int i = 0; i < repeat; i++) {
      makeSound();
    }
  }
}
public class Dog extends Animal {

  @Override
  public void makeSound() {
    System.out.println("Wooof.......");
  }
}
public class Cat extends Animal {

  @Override
  public void makeSound() {
    System.out.println("Meow.......");
  }
}
Animal[] animals = new Animal[5];
animals[0] = new Animal();
animals[1] = new Dog();
animals[2] = new Cat();
animals[3] = new Cat();
animals[4] = new Dog();

for(Animal a: animals) {
  a.makeSound(2);
}

Exercise Identify examples of method overloading vs. method overriding.

Solution

The makeSound method is overloaded in the Animal class and it is overridden in the Dog and the Cat classes.

Exercise Identify examples of static vs. dynamic polymorphism.

Solution
  • Static polymorphism: objects of (actual) type Dog and Cat are stored in an array with declared type of Animal.

  • Dynamic polymorphism: makeSound(2) inside the for-loop will need to call to overloaded makeSound (without argument). During runtime, the dispatch of makeSound will be based on the actual type of the Animal object a.

Resources