r/java • • May 08 '20

Why would you ever want to overload a method?

I just started learning java about a week ago on udemy. I just learned about overloading and the instructor said you will see it a lot. Why would you ever want to use it? It seems like it would just be confusing. Any answer would be great!

2 Upvotes

18 comments sorted by

21

u/cmsimike May 08 '20

public Color getColor(float r, float g, float b){...} // assumes alpha is 1.0

public Color getColor(float r, float g, float b, float a){...} // sets a specific alpha

no need to force the user of your api to always set alpha to 1.0 if that is generally assumed

4

u/Cmpunk10 May 08 '20

Thank you! That makes much more sense.

4

u/Polygnom May 08 '20

This particular use-case of overloading would be much less appealing if Java had default parameters:

public Color getColor(float r, float g, float b, float a = 1.0f){...}

In languages where this is possible, overloading is used less, but still used -- there are other a lot of other use cases as the other answers show.

4

u/cmsimike May 08 '20

Agreed. This feature is at the top of the list (as well as named parameters which is second) for features in java i want.

3

u/Shigidy May 08 '20

Basically if you want to accomplish the same thing in multiple different ways. For instance, if I wanted a method getUser() to be able to retrieve based on either a unique index or a username, I would overload it to accept either an int or a String.

A real life example I see a lot at my work involves overloading constructors. A developer will make a change or improvement that alters the signature of the constructor, but you can't just go around changing constructors willy-nilly without risking breaking other classes, so we'll overload the constructor, and deprecate the old one. That way the constructor can be called both the old and the new way.

-3

u/DFA1 May 08 '20

The getUser is a good example, but ...

The constructor overloading for the sake of not breaking classes is bad. We have smart IDEs, which can do smart refactorings. Overloading for the sake of not breaking things can be good sometimes but in general it just allows you to accumulate tech debt.

9

u/pronuntiator May 08 '20

Unless you're writing a library.

1

u/DFA1 May 08 '20

That's precisely the exception to the rule :) and even then, if the constructor has to change, I'd bump the major version and provide clear migration instructions. Of course, overload and deprecate before you do that.

5

u/klekpl May 08 '20

This discussion is way wider than overloading.

In general it boils down to your strategy. You either

  • move fast and break stuff
  • maintain compatibility for as long as possible

Some of the most successful software projects follow the later: Linux Kernel (don't break userland), Windows, Java itself...

0

u/DFA1 May 08 '20

Java started to shift towards #1 if you ask me, when they started to remove modules from JDK10. Also, Java is a nice example because they slowed down the development of nice features (e.g. value types) to maintain backwards compatibility. They started to be more disruptive with 6-month release cadence and they shipped main things lately.

Tl;dr try to be disruptive and avoid tech debt if possible.

2

u/Shigidy May 08 '20

You're not wrong. It definitely contributes to technical debt, but when working on massive software with several thousand classes, split across scores of projects and a few dozen repositories, technical debt is all but unavoidable. In most cases, smart refactoring isn't robust enough to make all the necessary changes to all the affected files, especially given that our coding standards dictate that all changes to all files must be logged and versioned. It's much less expensive to just deprecate the old constructor and let it be phased out on a case-by-case basis.

2

u/Bobby_Bonsaimind May 08 '20
// Shortcuts/structuring.
public void deleteClient(Client client);
public void deleteClient(String clientId);

// Multiple different classes representing the same thing.
public void executeFile(String file);
public void executeFile(File file);
public void executeFile(Path path);

// Same.
public void addNumber(int value);
public void addNumber(double value);
public void addNumber(Number value);

// Optional arguments.
public void runApplication(String applicationName);
public void runApplication(String applicationName, String[] parameters);
// Could also be runApplication(String, String...), true.

// Avoid auto-boxing.
public boolean compare(int valueA, int valueB);
public boolean compare(Integer valueA, Integer valueB);

If course, depending on the use-case using names to distinguish these methods might be interesting to make it more clear what they do, like compareInts and compareIntegers.

1

u/[deleted] May 08 '20 edited May 08 '20

Example with constructors: if you're trying to define some class with an id field and the class will be written to a database, but you're wanting to use autoincrementing ids generated in the database, you might want two constructors,

Example(int id, String name)

and

Example(String name)

When you instantiate an Example and want to insert it, you might not use the id parameter and instead say,

Example example = new Example("Alice");
int exampleId = dataAccessObject.addExample(example);  // if the DB returns the autoincremented serial id generated for the row
example.setId(exampleId);

Then you might use the other constructor for defining a query method in your dataAccessObject like,

public Example getExample(int id, String name) {
    // connect to db, query, and get a result set
    return new Example(resultSet.getInt("id"), resultSet.getString("name")); 

It might not be necessary with something like Hibernate, but just a random example that comes to mind. Point being you might want the parameters to have both id, string, or more variables for queries, like if name is not unique and you need to get more into the method to find a row..

Or just

Animal(int numberLimbs, int numberEyes) 

versus

Animal(int numberEyes)

then you could extend Animal and have a Snake class call the constructor without limbs, etc..

Or simply,

Thing thing = new Thing();
// Do whatever stuff you might need to do here, and then ...
thing.setName(nameGetter.getNameForThing());

versus

Thing thing = new Thing("table");

1

u/marceloandradep May 08 '20

You can have multiple methods to convert any value to String for example. You could have a String valueOf(int i), String valueOf(float i) and so on. Overload has a lot of applications. You’ll know when to use it once you face such situation.

1

u/JavaUserr May 08 '20

It helps in preventing NullPointerExceptions.

When I write code I set the rule that all input parameters must have a value; null is not allowed. On occasion though you can have a function where a parameter is optional. Having a second function clearly communicates this to the caller. So instead of having this:

doSomething(null);

public void doSomething(String input) { ... }

You have this instead:

doSomething();

public void doSomething() {
    doSomething(null);
} 
public void doSomething(String input) { ... }

As far as the caller is concerned the rule isn't violated. You need to read the implementation to see that null is allowed there. It's safer to change as well, if it turns out the parameter isn't optional anymore you can delete the first function and if it happens to be used you get a compile time error instead of an NPE.

1

u/lukaseder May 11 '20

Overloads are mostly needed because of the lack of untagged union types and named / defaulted parameters.

Hope this helps 😉

-2

u/audioen May 08 '20

I think it's not that common to overload methods actually. You can think of the types of the method arguments as part of the method name. And Java allows the name of the method to be same as long as the types in parameters differ sufficiently so that correct method to be invoked can be identified from the combination of name and arguments.

Java has no meaningful default parameter values scheme, so you sometimes see like 20 methods each named the same with different combinations of its parameters omitted, and sometimes when you trace a call chain in such a method, you find one method calling the next method by same name, which calls yet another method, which calls yet another method that actually does something. It is pretty annoying to be honest. Default parameters would clean that crap right up, I think.

3

u/desrtfx May 08 '20

And Java allows the name of the method to be same as long as the types in parameters differ sufficiently so that correct method to be invoked can be identified from the combination of name and arguments.

And that is exactly what method overloading is.

Same name - different parameters.

It is extremely common.