Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by gnat, MichaelT, GlenH7, jwenting, Bart van Ingen Schenau Jun 1 at 8:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer

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