0

I am following a textbook in which I have just come across method overloading. It briefly described method overloading as: when the same method name is used with different parameters its called method overloading.

From what I've learned so far in OOP is that if I want different behaviors from an object via methods, I should use different method names that best indicate the behavior, so why should I bother with method overloading in the first place?

1

2 Answers 2

6

Method overloading is typically used for variants of the same behavior:

  • Do the same thing for different types

  • A default version with fewer parameters and a complex version that allows more control via additional parameters.

A good example are the various massively overloaded methods in java.util.Arrays: they do the same thing on arrays of the various primitive types, as well as providing variants that e.g. operate only on a part of the array, or do things like sorting with a Comparator rather than the natural ordering.

2

You get consistency in naming. The real issue is human memory for method names, right? we find it easier to remember names that are commonly used and economy of typing, allowing for shorter method names? fewer different names means (mathematically) that the name itself carries less information.

Below is scenario ::

function Person FindPerson(string nameOfPerson) { ... }
function Person FindPerson(date dateOfBirth) { ... }
function Person FindPerson(int age, string dogsName) { ... }

is preferable to 'uniquely named' functions:

function Person FindPersonByName(string nameOfPerson) { ... }
function Person FindPersonByDOB(date dateOfBirth) { ... }
function Person FindPersonByAgeAndDogsName(int age, string dogsName) { ... }

This way the coder writing a client calling these functions can operate at a higher level of conceptual thinking ("I need to find a person") and doesn't need to remember- the compiler will be left to match the applicable overload.

Not the answer you're looking for? Browse other questions tagged or ask your own question.